Why does this small C program crash?

后端 未结 4 454
有刺的猬
有刺的猬 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?

提交回复
热议问题