Confusion about strcat with memcpy

429 views Asked by At

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 ?

2

There are 2 answers

2
Sourav Ghosh On

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 the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; [...]

1
R Sahu On

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:

  1. str1 points to a string literal, which is in read-only portion of the program.

  2. str1 does not enough memory to hold the string "HelloWorld" and the terminating null character.