-1

Possible Duplicate:
Why does char* cause undefined behaviour while char[] doesn’t?

The following code

int main() {
  char * st = "abc";
  *st = 'z';
  return 0;
}

is returning a segmentation fault. If the strings on the stack are not modifiable why is it not giving the error at compile time?

Community
  • 1
  • 1
user1198065
  • 210
  • 3
  • 10
  • 3
    the string literal is read-only. declare a char *array* instead. This is a **very** common question, btw. See [this question](http://stackoverflow.com/questions/8302290/why-does-char-cause-undefined-behaviour-while-char-doesnt/8302326#8302326), for an example. – WhozCraig Dec 23 '12 at 23:42
  • 3
    The string is not on the stack. It is in the Data Segment. (the pointer to the string is on the stack). – Steve Wellens Dec 23 '12 at 23:44
  • 1
    It does not give a compile time error for compatibility reasons. The type of `"abc"` would actually be `char const[4]` which _would_ give a compiler error. – K-ballo Dec 23 '12 at 23:45
  • 1
    @K-ballo Not in C, `"abc"` is a `const char[4]` in C++, but in C it's a `char[4]`. One that you mustn't attempt to modify, but the type doesn't tell you that. – Daniel Fischer Dec 24 '12 at 00:24

2 Answers2

2

The variable on the stack, st, is a pointer. The value assigned is to a string constant (read-only).

matthudson
  • 182
  • 6
1

char *str = "this is dangerous to modify"; is not a string in the same sense you get; it's called a string-literal and modifying it produces undefined behavior according to the standard.

If you want a string that you can later modify, go like this:

char str[] = "Some String";

then modify it accordingly.

Fingolfin
  • 5,363
  • 6
  • 45
  • 66