Segmentation Fault With Char Array and Pointer in C on Linux

对着背影说爱祢 提交于 2019-11-27 14:03:32

one points directly to the string located in a read-only page. On the other hand, two is an array allocated on the stack and is initialized with some constant data. At run time, the string in the read only section of the executable will be copied to the stack. What you are modifying is the copy of that string on the stack, not the read-only memory page.

At a higher level perspective, from the language point of view, "abcd" is an expression of type const char* and not char*. Thus, modifying the value pointed by such an expression results in undefined behavior. The statement char* one = "something"; merely stores the pointer to the string in a variable (unsafely, since it's casting away const modifier). The char two[] = "something"; is totally different. It's actually declaring an array and initializing it, much like int a[] = {1,2,3};. The string in quotes here is the initialization expression.

The "another" you see in the rodata section is what will be copied in the array two when it will be initialized. On the other hand the address of the string "computer" will be assigned to one.

So, one is pointing to a read only segment (and hence the segfault on write) while two will be allocated on the stack and then "another" will be copied into it.

The second form creates an array by copying the literal string.

It is equivalent to:

char two[] = {'a', 'n', 'o', 't', 'h'. 'e', r', '\0'};

You can initialize a character array with variables, such as

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