Possible Duplicate:
Why do I get a segmentation fault when writing to a string?
What is the difference between char a[] = “string”; and char *p = “string”;
Can anyone point out the problem in following program:
#include <stdio.h>
int main()
{
char *c = "Hello World!! !!";
char c2 = 'X';
while(c)
{
if(*c == ' ')
{
printf("%s",c);
*c = c2;
}
c++;
}
return 0;
}
It crashes at *c = c2; with following error :
Thread [1] (Suspended : Signal : EXC_BAD_ACCESS:Could not access memory)
main() at mainclass.cpp:64 0x100000d74
I used GCC as compiler on MAC OSX and Eclipse as IDE.
In your code,
cpoints to a string literal. The line*c = c2tries to modify the string literal, which is undefined behaviour. One possible manifestation of the undefined behaviour is that string literals are put into read-only memory and you get aSIGSEGVor similar.If you change the code as follows, it should work:
Now
cpoints into an array. Unlike string literals, it is permissible to modify the contents of an array.Lastly, your while-loop is incorrectly conditioned on the value a pointer, not the value it points to. You’re looking for a null-terminator (‘\0’). It should look like this: