Sunday, July 12, 2009

Why does the following C code give segmentation fault?

#include%26lt;stdio.h%26gt;


#include%26lt;string.h%26gt;


int main()


{


char *p="Hello";


printf("%s\n",p);


printf("%c\n",*p);


*(p)='A'; /*Replace the first letter with 'A'*/


printf("%s\n",p);


return 0;


}








I am using Linux operating system. In windows probably it will not give a segmentation fault.

Why does the following C code give segmentation fault?
Please see http://c-faq.com/decl/strlitinit.htmll .





You're creating a constant string literal, and then trying to modify it. Effectively, you're trying to write over read-only memory, and this is why a segfault occurs.





You could use Windows if you suffer from the "blame Linux" mentality. You'll get a segfault anyway, though.
Reply:To be able to manipulate bytes using a pointer, try using malloc to allocate a block of memory.


char *p = malloc(6);


strcpy(p, "Hello"); // copy string with trailing \0


*p = 'A';





The code you are using points p to a string in a constant table, and the program cannot write to the address.
Reply:As another person explained, you're replacing the


contents of the literal string "Hello", which the


compiler implementation is allowed (but not required)


to place into a read-only memory segment.





For example, on Solaris using the Sun compiler, this


does not cause a segmentation violation by default.


However, if you compile with the "-xstrconst" option


(which puts literal constants in read-only memory),


then of course, it does. The point is that it will


vary from platform to platform.
Reply:Don't use char *p="Hello";





Use





unsigned char p[] = "Hello";





#include%26lt;stdio.h%26gt;


#include%26lt;string.h%26gt;


int main()


{


unsigned char p[]="Hello";


printf("%s\n",p);


printf("%c\n",p[0]);


p[0]='A'; /*Replace the first letter with 'A'*/


printf("%s\n",p);


return 0;


}





The static allocations by the complier are just that "static". For even more fun, compile your "broken" program with full optimization. You'll get no errors and of course no "Aello". The compiler optimizes out the write to read-only segments.


No comments:

Post a Comment