Simple C code works fine on HPUX, but segfaults on Linux. What for?

For a long time I did not make serious C, and I would really like to get a brief explanation. The following code compiles and works fine on HP / UX. It compiles without warning in GCC 4.3.2 on Ubuntu (even with gcc -Wall), but segfaults when run on Linux.

Can someone explain why?

#include <stdio.h> int main() { char *people[] = { "Abigail", "Bob" }; printf("First: '%s'\n", people[0]); printf("Second: '%s'\n", people[1]); /* this segfaults on Linux but works OK on HP/UX */ people[1][0] = 'R'; printf("First: '%s'\n",people[0]); return(0); } 
+4
source share
3 answers

Your people array is actually char const *people[] . Literal strings are usually stored in read-only memory on many systems. You cannot write to them. This does not seem to apply to HP / UX.

+8
source

String literals are in a read-only data segment. Trying to write to them is a violation of segmentation.

+2
source

You cannot modify string literals.

0
source

All Articles