You didn't malloc enough space. sizeof(char *)
is the amount of memory required to hold a pointer (NOT anything to do with where that pointer is pointing).
Change both mallocs to: malloc(sizeof str)
, or malloc(strlen(str) + 1)
.
Also, str2 = str1
causes a memory leak. It makes the pointer str2
point to where str1
points, and then you have that malloc'd block with nothing pointing to it.
In your original code, when you write into memory you don't own, anything could happen; it's not really useful to try and investigate exactly why you get some particular garbage instead of some other particular garbage.