Modifying value of char pointer in c produces segfault

前端 未结 2 613
悲&欢浪女
悲&欢浪女 2020-12-12 06:48

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

#include
int main() {
         


        
相关标签:
2条回答
  • 2020-12-12 07:06

    Attempting to modify a string literal causes undefined behaviour.

    0 讨论(0)
  • 2020-12-12 07:15

    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.

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