Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault when using strcat (minimal example)

Tags:

c

I want to add "$" to the end of the string, I've seen that I can use strcat() and I wrote the following code:

char *word = "1000";
const char *dollar = "$";
strcat(word,dollar);
printf("%s", word);

It compiles, but when I run the little program I get Segmentation fault (core dumped). Where is the error?

I know that strcat is: char *strcat(char *dest, const char *src);

like image 889
DarkCoffee Avatar asked Jul 04 '26 09:07

DarkCoffee


1 Answers

The problem is that you are trying to concatenate to a literal string. Literal strings are constant and can not be changed.

You need to create the "destination" as an array instead, containing enough characters to fit your concatenation:

char word[16] = "1000";

The number 16 in the array above I picked arbitrary. It has to be at least big enough to fit the string you put in it, plus the length of the string you concatenate, plus the terminating '\0' character.

like image 161
Some programmer dude Avatar answered Jul 06 '26 22:07

Some programmer dude