str1[size] = '\0';
writes beyond the allocated memory, thus your program crashes. You should allocate one more for the 0
character.
The other error is that you call your function fro char*
as first argument (ptr3
and ptr4
) that are not initialized. This has undefined behavior, anything can happen with such code.
A proper way would be to check if that argument is 0
and then just call malloc
with the appropriate size. But for such an approach to work you would have to properly initialize these variables with 0
, which you should do, anyhow.
Also, don't cast the return of malloc
and relatives, this might hide subtle bugs.