0
void main() {
    char *x;
    x="abc";
    *x='1';
}

Why it comes with error "Access violation writing location"?

I cannot assign value to x by *x='1'?

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
user2756494
  • 263
  • 1
  • 4
  • 7

3 Answers3

3

Modifying string literals leads to undefined behavior, try using char arrays instead:

int main() {
    char x[] = "abc";
    *x ='1';
}

Also note you should use int main().

Or if you prefer to use pointers, use this a little redundant example:

int main() {
    char x[] = "abc";
    char *y = x;
    *y ='1';
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • void strcpy(char *s, char *t) { while((*s = *t) != '\0') { s++; t++; } } – user2756494 Sep 07 '13 at 07:37
  • 1
    @user2756494 I assume you mean this function violates the rule? That's not true, the first parameter passed to `strcpy` should never be a string literal. The rule isn't against modifying `char` pointers, it's against modifying string literals. – Yu Hao Sep 07 '13 at 07:40
0

Thats wrong because you are attempting to modify a string literal. It is created in readonly mode and if you will try to change that then it would be an access violation and hence result in error.

As a solution as to how it can be achieved you can try using char arrays

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

The application is loaded in several memory regions (memory pages), code read-only executable (program counter can run in it), and string literals might ideally go into a read-only region.

Writing to it would give an access violation. In fact is nice that you get that violation, are you running Windows? That would possitively surprise me.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138