you need to understand the function of the assignment operator (i.e., =
). think of what happens when you do something like
int i = GetInt();
i = 20;
after assigning 20
to i
, can we get whatever was in i
before the assignment (the value returned by GetInt
) back?
well, unless we stored it in another variable or something, apparently we can't. that's because, assuming the assignment went well (i.e., no errors, etc), assigning a value to a variable overwrites the previous value (whatever was in there before the assignment) forever.
now when you do
char* dest;
char* src;
dest = malloc(16);
src = malloc(11);
no problem with that. you're obviously defining two pointers, allocating memory for them on the heap by calling malloc
which according to its man page returns the address of the allocated memory (if the allocation was successful). the returned addresses are stored in the pointers normally.
but when you then do that
dest = "text/";
src = "javascript";
you're not storing "text/"
and "javascript"
into the memory pointed to by dest
and src
respectively. rather you're losing the addresses that were in there forever and having the pointers pointing to these strings instead.
string literals in C are compile-time constants. they are stored in a read-only data segment in memory and they cannot be modified. so now the pointers are pointing to locations on a read-only memory.
the call to strcat(dest, src)
tries to modify the memory pointed to by dest
(which recall should not be modified) so you get a segfault.
the fix:
you may use a function like strcpy
from the standard library to initialize the memory pointed to by the pointers after allocating memory for them. execute man strcpy
for more info!