简体   繁体   中英

Why does this small C program crash?

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.

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.

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 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM