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
A completely different solution would be this:
The nice thing about
snprintf
is that it returns the number of characters it would write if there was enough space. This can be used by measuring upfront how much memory to allocate which makes complicated and error-prone calculations unnecessary.If you happen to be on a system with
asprintf
, it's even easier:For a start, if this is your code:
then
name_log
is 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
user
appears to be, probably the safest option is to allocate another string large enough to hold the result, something like:The
malloc
ensures you have enough space to do all the string operations safely, enough characters for the three components plus a null terminator.the name_log is pointed at a static place: "log-", which means is could not be modified, while as the first parameter in
strcat()
, it must be modifiable.try changing name_log's type
char*
intochar[]
, e.g.you need to allcocate memory. You cannot add to a string in this way as the string added goes to memory which hasnt been allocated.
you can do
string literals get allocated a fixed amount of memory, generally in a read only section, you instead need to use a buffer.
On a side note,
strcat
is generally unsafe, you need to use something that that checks the size of the buffer it uses or with limits on what it can concatenate, likestrncat
.