Reputation: 3217
Okay so I have seen a few implementations of the strcat function with memcpy. I understand that it is efficient, since there no need to allocate. But how do you preserve overwriting the contents of the source string with the resultant string.
For example lets take-:
char *str1 = "Hello";
char *str2 = "World";
str1 = strcat(str1, str2);
How do I ensure that in str2
isn't overwritten with the contents of the resultant "HelloWorld" string ?
Also if strings are nothing but char arrays, and arrays are suppose to have a fixed size then without reallocation of memory if I copy bytes into the array that are larger than the array, then isn't that unsafe ?
Upvotes: 0
Views: 442
Reputation: 206627
I understand that it is efficient, since there no need to allocate.
That's an incorrect understanding. Neither memcpy
nor strcat
allocates memory. Both require that you pass pointers that point to sufficient amount of valid memory. If that is not the case, the program is subject to undefined behavior.
Your posted code is subject to undefined behavior for couple of reasons:
str1
points to a string literal, which is in read-only portion of the program.
str1
does not enough memory to hold the string "HelloWorld"
and the terminating null character.
Upvotes: 1
Reputation: 134346
It's not about unsafe, it's undefined behavior.
First of all, you're trying to modify a string literal, which inherently invokes UB.
Secondly, regarding the size of the destination buffer, quoting the man page (emphasis mine)
The
strcat()
function appends thesrc
string to thedest
string, overwriting the terminating null byte ('\0'
) at the end ofdest
, and then adds a terminating null byte. The strings may not overlap, and thedest
string must have enough space for the result. Ifdest
is not large enough, program behavior is unpredictable; [...]
Upvotes: 1