The issue, as others have mentioned, is that you're not allocating enough space for the string you want to copy. strlen
returns the number of characters in the string, however that number doesn't include the null byte at the end that terminates the string.
So when you call strcpy
, you're writing one byte past the end of the allocated memory. Once you write past your memory bounds, that invokes undefined behavior. That means your program might appear to work, it might crash (sometimes right away, sometimes later), or it might cause data corruption that would be hard to detect.
In this particular situation, the extra byte you wrote probably corrupted data used by the implementation of free
and/or malloc
. But with some other compiler or OS, it might work fine.
So to avoid undefined behavior, be sure to allocate the required amount of space:
char* str2 = malloc(strlen(str1) + 1);
Also, don't cast the return value of malloc
, as that may mask other errors in your code.