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;
}
12
  • 5
    This question gets asked about once a week on SO :), give me a minute to find the original and I'll link you to it. Commented Jun 22, 2009 at 7:43
  • 1
    C or C++? Knowing which language you are coding in would be useful. Commented Jun 22, 2009 at 7:45
  • 1
    @ Sev: Let me answer that: Because myString is a char array (i.e., C-style string), and *myString is the first character in the array. "5" is actually { '5', '\0' }.
    – DevSolar
    Commented Jun 22, 2009 at 7:46
  • 5
    Duplicae of stackoverflow.com/questions/164194/… Commented Jun 22, 2009 at 7:46
  • 1
    Here's one thread: stackoverflow.com/questions/1011455/… Commented Jun 22, 2009 at 7:48

3 Answers 3

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.

2

String literals are considered constant.

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.