I had an embarrassing struggle with this simple thing, as this was segfaulting:
#include <stdio.h>
int main()
{
char *test = "this is a string";
test[0] = 'q';
printf(test);
return 0;
}
but this was not:
#include <stdio.h>
int main()
{
char test[] = "this is a string";
test[0] = 'q';
printf(test);
return 0;
}
After looking at the assembly I noticed that in the first case, the literal "this is a string"
was declared in .rodata
, so that explains the segfault. But in the second case, the string wasn't in the assembly at all, so I assume it was being linked via the .data section as writable. Why this difference in behavior? Is this obvious and I'm being stupid?