Why does this small C program crash?

后端 未结 4 425
有刺的猬
有刺的猬 2021-01-28 12:33

The program is:

#include 
#include 
int main(void) {
    char *a=\"abc\",*ptr;
    ptr=a;
    ptr++;
    *ptr=\'k\';
    printf(\"         


        
相关标签:
4条回答
  • 2021-01-28 12:49

    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?

    0 讨论(0)
  • 2021-01-28 12:56

    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.

    0 讨论(0)
  • 2021-01-28 13:08

    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.

    0 讨论(0)
  • 2021-01-28 13:09

    This:

    char *a="abc";
    

    is really:

    const char *a="abc";
    

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

    0 讨论(0)
提交回复
热议问题