Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 segfaults on Linux but works OK on HP/UX */
   people[1][0] = 'R';

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

   return(0);
}
like image 273
Tom Avatar asked Dec 28 '22 17:12

Tom


1 Answers

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.

like image 72
Rudy Velthuis Avatar answered Feb 22 '23 22:02

Rudy Velthuis