0

I have the following simple code:

char *a = "aaaa";
*a = 'b'; // error here: access violation writing location

Can anyone explain the reason of getting this error? Does it mean I cannot edit a after it's been initialised?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055

1 Answers1

2

String literals are immutable. You are not allowed to attempt to modify them.

char* a = "aaaa";         // deprecated!
*a = 'b';                 // unsafe & undefined

Your compiler should be warning you that, actually, your code should read:

const char* a = "aaaa";   // OK
*a = 'b';                 // can't compile

The const prevents it from even compiling.

I notice that the problem in your previous question was also caused by not heeding warnings (and/or having them switched off). Read your compiler's warnings.

It looks like Microsoft Visual Studio 2012 doesn't emit any warning, though, which is really sad.

Anyway, if you want to copy the string literal's contents into a local copy:

char a[] = "aaaa";        // OK: a copy
*a = 'b';                 // OK
Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055