user3126987
user3126987

Reputation:

Access violation writing location when modifying char *

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?

Upvotes: 0

Views: 583

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385204

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

Upvotes: 2

Related Questions