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)