0

Why does the following code prompt segmentation fault?

#include <stdio.h> #include <string.h> int main() { char b = 'X'; char *d = " "; for(int i = 0;i<20;i++){ printf("%s %c",d,b); strcat(d," "); } return 0; }

14th Sep 2020, 2:34 PM
Phyo Htet Aung
Phyo Htet Aung - avatar
2 odpowiedzi
+ 4
According to http://www.cs.ecu.edu/karl/2530/spr17/Notes/C/String/nullterm.html "... strcat is not a concatenation function... It adds b to the end of the string in array a. So what is in array a is changed. Also, there must be enough room to add b to a. Strcat will not allocate more room. " When you do char* d = " "; you are not allocating any memory to d, you are just creating a char pointer which points to the first character in the literal " ". When you call strcat using d, strcat expects to be able to add to d, but fails and writes out of bounds. Segfault takes place. Observe what happens when you do: char d[25] = " "; // just above 20 to be sure // either that, or malloc to char* d
14th Sep 2020, 3:00 PM
Hatsy Rei
Hatsy Rei - avatar
0
Because the source string in your strcat() is `char *d = " "` which in this case it is a string literal and stored in static memory (*a read-only string*). It causes segfault because you're trying to modify unmodifiable. That's what I know, my answer might be false or not detailed.
15th Sep 2020, 11:14 PM
LastSecond959
LastSecond959 - avatar