4

Possible Duplicate:
Why does simple C code receive segmentation fault?

I am working in Ubuntu using the GCC compiler with C language; I have this program:

void foo(char *word)
{
    //something stupid
    *word = 'z';
}

int main()
{

    char word1[] = "shoe";
    char *word2 = "shoe";

    foo(word1);
    printf("%s", word1);
    foo(word2);
    printf("%s", word2);
}

So what's the difference? With the latter I get a segmentation fault error.

Community
  • 1
  • 1
elios264
  • 385
  • 2
  • 16

3 Answers3

5

The difference is that the first one is valid code, whereas the behaviour of the second one is undefined (since you are not allowed to modify a string literal). See the FAQ.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    If I had a dollar for every time someone asked about modifying a `const char*`... – Ed S. Jan 05 '12 at 23:15
  • @EdS.: But it *isn't* a `const char*`. String literals in C are not `const`; it's just undefined behavior to attempt to modify them. (They are `const` in C++.) – Keith Thompson Jan 05 '12 at 23:26
  • Right, it is a poor design decision. They *should* be const, but I admit I missed the C tag and assumed C++. – Ed S. Jan 05 '12 at 23:39
3

char word1[] = "shoe"; creates an array of 5 characters and copies the string literal "shoe" into it (which can be modified).

char *word2 = "shoe"; creates a pointer to the string literal "shoe" (which cannot be modified).

Krizz
  • 11,362
  • 1
  • 30
  • 43
1

The problem is your char *word2 = "shoe"; is being stored in the .rodata data section:

$ readelf -p .rodata adum

String dump of section '.rodata':
  [     4]  shoe
  [     9]  %s

(This would be easier to see if you stored shoe in one variable and foot in the other variable.)

The compiler is allowed to store the string constant in read-only memory because the standard doesn't allow modifying string literals.

Your first case is an explicitly-initialized character array; the standard does allow modifying those, so they are not stored in a read-only section.

sarnold
  • 102,305
  • 22
  • 181
  • 238