Your code is wrong.
You are allocating space for a single pointer (malloc(sizeof(char*))
), but no characters. You are overwriting your allocated space with all the strings, causing undefined behavior (in tihs particular case, corrupting malloc()
‘s book-keeping data).
You don’t need to allocate space for the pointer (res
), it’s a local variable. You must allocate space for all the characters you wish to store at the address held by the pointer.
Since you’re going to be traversing a list to find strings to concatenate, you can’t know the total size upfront. You’re going to have to do two passes over the list: one to sum the strlen()
of each string
, then allocate that plus space for the separator and terminator, then another pass when you actually do the concatenenation.