0

The program is:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    char *a="abc",*ptr;
    ptr=a;
    ptr++;
    *ptr='k';
    printf("%c",*ptr);
    return 0;
}

The problem is in the

*ptr='k';  

line, when I remove it program works normally. But I can't figure out the reason.

Sunny88
  • 2,860
  • 3
  • 24
  • 25
  • A very good explanation of this problem can be found [here](http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c) – JediLlama Jan 09 '12 at 05:25

4 Answers4

6

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

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?

Community
  • 1
  • 1
ChrisWue
  • 18,612
  • 4
  • 58
  • 83
0

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.

Jim Buck
  • 20,482
  • 11
  • 57
  • 74
  • 1
    Correction: it's in memory that may or may not be read-only. It's completely allowable for this to run to completion and print out the modified string. Another possibility is that it will modify a another string literal with the same value. For example: `int main() { char *s="abc"; s[1] = 'd'; printf("abc"); }` might print out `adc`. – Jerry Coffin Jan 09 '12 at 05:17
  • In the OP's case, it's definitely because of read-only memory. But, true, I've seen what you pointed out before (on PlayStation1).. we had to purposely make our strings different if we planned to change one of them. (Fun times.) – Jim Buck Jan 09 '12 at 05:42
0

This:

char *a="abc";

is really:

const char *a="abc";

You can't modify ptr, which points to the same address as a.

Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345