Modifying value of char pointer in c produces segf

2019-01-20 19:20发布

The following code produces a segmentation fault on my system. I can't figure out why. Any help would be appreciated.

#include<stdio.h>
int main() {
    char * a = "abc";
    *a = 'c';
    printf("%c\n", *a);
    return 0;
}

2条回答
【Aperson】
2楼-- · 2019-01-20 20:05

The standard explicitly lists this as undefined behavior in §J.2:

— The program attempts to modify a string literal (6.4.5)

If you want to copy it into a local array, do:

char a[] = "abc";

a is an array on the stack, and you can modify it freely.

查看更多
倾城 Initia
3楼-- · 2019-01-20 20:19

Attempting to modify a string literal causes undefined behaviour.

查看更多
登录 后发表回答