0

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

int main()
{
    char *c = "abc";
    *c = 'd';
    printf("%s",c);
    return 0;
}

When I tried to run this program in C then the program crashes..I want to know what is the error here?

Community
  • 1
  • 1
som
  • 481
  • 1
  • 4
  • 9

2 Answers2

3

Because the string literal abc is actually stored in a read-only area of the process and you are not supposed to modify it. The operating system has marked the corresponding pages as read-only and you get a runtime exception for an attempt to write there.

Whenever you assign a string literal to a char pointer, always qualify it as const to make the compiler warn you about such problems:

const char *c = "abc";
*c = 'd'; // the compiler will complain

If you really want to modify a string literal (although not directly itself, but its copy), I would suggest using strdup:

char *c = strdup("abc");
*c = 'd'; // c is a copy of the literal and is stored on the heap
...
free(c);
Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
1

"abc" is a string literal.

*c = 'd' is an attempt to modify that string literal.

You cannot modify string literals.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680