The program is:
#include
#include
int main(void) {
char *a=\"abc\",*ptr;
ptr=a;
ptr++;
*ptr=\'k\';
printf(\"
Because "abc" is a constant string literal. Then you point ptr
to it and try to modify it which is undefined behaviour. Typically string literals are put in a memory section which gets mapped as read-only - hence the access violation.
See also this question: String literals: Where do they go?
The problem is because you are trying to change the string literal "abc"
with:
char *a="abc",*ptr;
ptr=a; // ptr points to the 'a'.
ptr++; // now it points to the 'b'.
*ptr='k'; // now you try to change the 'b' to a 'k'.
That's undefined behaviour. The standard explicitly states that you are not permitted to change string literals as per section 6.4.5 String literals
of C99:
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
It will work if you replace:
char *a="abc",*ptr;
with:
char a[]="abc",*ptr;
since that copies the string literal to a place that's safe to modify.
The reason is that your string "abc"
lives in a read-only area of memory. It gets put there by the linker. You try to change it in your program, and all bets are off.
This:
char *a="abc";
is really:
const char *a="abc";
You can't modify ptr
, which points to the same address as a
.