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,513
  • 5
  • 41
  • 72

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
  • 120,187
  • 20
  • 207
  • 252
2

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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
  • 167,383
  • 100
  • 513
  • 979
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
  • 8,018
  • 11
  • 53
  • 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
  • 21,161
  • 6
  • 59
  • 101
0

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

Martin James
  • 24,453
  • 3
  • 36
  • 60