In fact, strcat(dest, src)
searches for a null byte starting with dest
and ending in, and then writes the string src
.
After malloc
contents of the memory are undefined, so your current code can do any number of things, most of which are incorrect. If you execute concat[0] = 0
before strcat
, then your code works, but you have to look for the length of str1
three times - once for strlen
, again for the first strcat
and the last for the second strcat
.
Instead, I recommend using memcpy:
size_t len1 = strlen(str1), len2 = strlen(str2); char *concat = (char*) malloc(len1 + len2 + 1); memcpy(concat, str1, len1); memcpy(concat+len1, str2, len2+1);
This takes advantage of the fact that you know from the very beginning where you want the bytes of both lines to go through and how many there are.
source share