1

Possible Duplicates:
Why does simple C code receive segmentation fault?
Modifying C string constants?

Why does this code generate an access violation?

int main()
{
    char* myString = "5";
    *myString = 'e'; // Crash
    return 0;
}
Community
  • 1
  • 1
0xC0DEFACE
  • 8,825
  • 7
  • 34
  • 35

3 Answers3

5

*mystring is apparently pointing at read-only static memory. C compilers may allocate string literals in read-only storage, which may not be written to at run time.

Avi
  • 19,934
  • 4
  • 57
  • 70
2

String literals are considered constant.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
0

The correct way of writing your code is:

const char* myString = "5";
*myString = 'e'; // Crash
return 0;

You should always consider adding 'const' in such cases, so it's clear that changing this string may cause unspecified behavior.

inazaruk
  • 74,247
  • 24
  • 188
  • 156