0

Possible Duplicate:
Why does this Seg Fault?

I receive a segmentation fault when using ++ operator on a char *

#include<stdio.h>

int main()
{
    char *s = "hello";
    printf("%c ", ++(*s));
    return 0;
}

But if I do the following:

#include<stdio.h>

int main()
{
    char *s = "hello";
    char c = *s;
    printf("%c ", ++c);
    return 0;
}

Then the code compiles perfectly, what is the problem with the above code?

Community
  • 1
  • 1
Kartik Anand
  • 4,257
  • 5
  • 40
  • 70

6 Answers6

5

The first code snippet is attempting to modify a character in a string literal as:

++(*s)

is attempting to increment the first character in s. String literals are (commonly) read-only and an attempt to modify will cause the segmentation fault (the C standard states If the program attempts to modify such an array, the behavior is undefined.).

The second snippet is modifying a char variable, which is not read-only as after:

char c = *s;

c is a copy of the first character in s and c can be safely incremented.

hmjd
  • 117,013
  • 19
  • 199
  • 247
2

In the first case you modify a constant literal, and in the second you modify a variable.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585
2

This code:

printf("%c ", ++(*s));

tries to modify a string literal through a pointer to one of its characters. Modifying string literals is undefined behavior - the quite likely outcome is that string literals are often stored in read-only memory, so it's technically illegal to modify them and that's why it manifests itself as segmentation fault on your system.

sharptooth
  • 163,328
  • 92
  • 501
  • 942
1

char *s = "hello";

This implies that 's' is a const string.

If you need a non-const string, you should allocate it explicitly from heap.

ciphor
  • 7,720
  • 10
  • 48
  • 70
1

You are trying to change a string literal in the first case which is not allowed. In the second case you create a new char from the first character of the string literal. You modify the copy of that character and that is why the second case works.

mathematician1975
  • 20,781
  • 6
  • 55
  • 98
0

Your code does not have write permission for the segment where the string literal is stored.

Martin James
  • 23,993
  • 3
  • 34
  • 58