Why does this code produce runtime issues:
char stuff[100]; strcat(stuff,"hi "); strcat(stuff,"there");
but this doesn't?
char stuff[100]; strcpy(stuff,"hi "); strcat(stuff,"there");
The strcpy() function copies one string into another. The strcat() function concatenates two functions.
The strcat() function copies the string addressed by the second pointer argument, s2 , to the location following the string addressed by the first pointer, s1 . The first character of s2 is copied over the terminating null character of the string addressed by s1 .
Threadsafe: Yes. The strcat() function concatenates string2 to string1 and ends the resulting string with the null character. The strcat() function operates on null-ended strings.
The strncpy() and strncat() functions are similar to the strcpy() and strcat() functions, but each has an additional size_t parameter n that limits the number of characters to be copied. These functions can be thought of as truncating copy and concatenation functions.
strcat
will look for the null-terminator, interpret that as the end of the string, and append the new text there, overwriting the null-terminator in the process, and writing a new null-terminator at the end of the concatenation.
char stuff[100]; // 'stuff' is uninitialized
Where is the null terminator? stuff
is uninitialized, so it might start with NUL, or it might not have NUL anywhere within it.
In C++, you can do this:
char stuff[100] = {}; // 'stuff' is initialized to all zeroes
Now you can do strcat, because the first character of 'stuff' is the null-terminator, so it will append to the right place.
In C, you still need to initialize 'stuff', which can be done a couple of ways:
char stuff[100]; // not initialized stuff[0] = '\0'; // first character is now the null terminator, // so 'stuff' is effectively "" strcpy(stuff, "hi "); // this initializes 'stuff' if it's not already.
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