All of the code below on C.
Both the code snippet below are compiled, but the difference is that the second program crashes at startup.
One:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char *str[80];;
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
Two:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char *str="";
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
The difference is that in the first case, said the size of the str
string, while the second is not. How to make string concatenation without a direct indication of the size of the string str
?
The difference is that in the first case, said the size of the str string, while the second is not.
No. In the first program, the following statement
char *str[80];
defines str
to be an array of 80
pointers to characters. What you need is a character array -
char str[80];
In the second program,
char *str="";
defines str
to be a pointer to the string literal ""
, not an array. Arrays and pointers are different types.
Now, the second program crashes because
char *str="";
defines str
to be a pointer to a string literal. The first argument of strcpy
should be a pointer to a buffer which is large enough for the string to be copied which is pointed to by its second argument.
However, str
points to the string literal ""
which is allocated in read-only memory. By passing str
to strcpy
, it invoked undefined behaviour because strcpy
tries to modify it which is illegal. Undefined behaviour means the behaviour is unpredictable and anything can happen from program crash to due to segfault (illegal memory access) or your hard drive getting formatted. You should always avoid code which invoked undefined behaviour.
How to make string concatenation without a direct indication of the size of the string str?
The destination string must be large enough to store the source string else strcpy
will overrun the buffer pointed to by its first argument and invoke undefined behaviour due to illegal memory access. Again, the destination string must have enough space for the source string to be appended to it else strcat
will overrun the buffer and again cause undefined behaviour. You should ensure against this by specifying the correct size of the string str
in this case.
Change to:
One:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
Two:
#include <stdio.h>
#include <string.h>
void main() {
char *foo = "foo";
char *bar = "bar";
char str[80]="";
strcpy (str, "TEXT ");
strcat (str, foo);
strcat (str, bar);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With