Here is my code :
char *name, name_log="log-";
——getting ‘name’ from user—–
strcat(name_log, name);
char ext[] = ".log";
strcat(name_log, ext);
What i need to end up with is name_log = “log-‘name’.log” but Im getting a segmentation fault error :((. What am I doing wrong and how can I fix it ? Thx
For a start, if this is your code:
then
name_logis a char, not a char pointer.Assuming that’s a typo, you cannot append to string literals like that. Modifications to string literals are undefined behaviour.
For a variable sized string, as
userappears to be, probably the safest option is to allocate another string large enough to hold the result, something like:The
mallocensures you have enough space to do all the string operations safely, enough characters for the three components plus a null terminator.