简体   繁体   中英

Confusion about strcat with memcpy

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 ?

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; [...]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM