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; }
2 Respostas
+ 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
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.