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'
?
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'
?
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';
}
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
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.