Possible Duplicate:
can’t modify char* – Memory access violation
Been tracking down a problem in a c-program I compile with MingW,
and it finally boiled down to the very simple testcase below.
The intention, of course, is to change a character in a string.
But this code gives me a Segmentation fault.
Can someone please explain why? I dont get it…
test.c:
#include <stdio.h>
main(){
char *s = "xx";
printf("(%s)\n", s);
s[0] = 'z'; // ** Segmentation fault here **
printf("(%s)\n", s);
}
—
$ gcc -c test.c
$ gcc -o test.exe test.o
$ ./test.exe
(xx)
Segmentation fault
The string “xx” can be allocated into read-only memory by the compiler. Hence, when you try to change that memory, if it has been allocated to read-only memory you’ll get a segmentation fault.
In cases that your string size is fixed, such as in your example, if you define the string as a character array that memory will not be allocated read-only and you will not have that problem.
Sometimes, you don’t know the string’s maximum size or you don’t want to waste space, so you’d need to malloc() that memory, use strdup() (which allocates memory as part of its function), or something similar.