Modifying value of char pointer in c produces segfault

雨燕双飞 提交于 2019-11-27 08:53:54

问题


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;
}

回答1:


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.




回答2:


Attempting to modify a string literal causes undefined behaviour.



来源:https://stackoverflow.com/questions/5189782/modifying-value-of-char-pointer-in-c-produces-segfault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!