开发者

Simple C code works fine on HPUX but segfaults on Linux. Why?

I have not done any serious C in a long, long time and would appreciate a quick explanation. The following code compiles and runs fine on HP/UX. It compiles without any warning on GCC 4.3.2 in Ubuntu (even with gcc -Wall), but segfaults when run on Linux.

Can anyone explain why?

#include <stdio.h>

int main() {
    char *people[] = { "Abigail", "Bob" };

   printf("First:  '%s'\n", people[0]);
   printf("Second: '%s'\n", people[1]);

   /* this s开发者_StackOverflowegfaults on Linux but works OK on HP/UX */
   people[1][0] = 'R';

   printf("First:  '%s'\n",people[0]);

   return(0);
}


Your people array is in fact a char const *people[]. Literal strings are typically in read-only memory on many systems. You can't write to them. Apparently, this is not the case on HP/UX.


The string literals are in a read-only data segment. Attempting to write to them is a segmentation violation.


You cannot modify string literals.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜