分割故障原因在Linux字符数组和指针用C [英] Segmentation Fault With Char Array and Pointer in C on Linux

查看:110
本文介绍了分割故障原因在Linux字符数组和指针用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下程序:

int main(){
  char* one = "computer";
  char two[] = "another";
  two[1]='b';
  one[1]='b';
  return 0;
}

它出现segfaults,因为,要必须在读取内存指针一点只读存储器这是有道理的行[1] ='B'。然而,问题是为什么不就行两[1] ='B'段错误?纵观汇编输出从GCC:

It segfaults on the line "one[1]='b'" which makes sense because the memory that the pointer "one" points to must be in read only memory. However, the question is why doesn't the line "two[1]='b'" segfault? Looking at the assembly output from gcc:

.file   "one.c"
        .section        .rodata
.LC0:
        .string "computer"
.LC1:
        .string "another"
        .text
.globl main
        .type   main, @function
main:

我们看到,两个字符串都在rodata部分,因此它们是只读的。那么接下来怎么来行两[1] ='B'不段错误?

We see that both strings are in the rodata section so they are readonly. So then how come the line "two[1]='b' does not segfault?

推荐答案

有一个直接指向位于只读页字符串。在另一方面,两个是在栈上分配的数组,并与一些常量数据初始化。在运行时,在可执行的只读部分中的串将被复制到堆栈中。你所修改的是字符串的堆栈上的副本,而不是只读内存页。

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.

在更高的层次来看,从语言角度,ABCD的类型为const char的前pression * ,而不是的char * 。因此,修改由未定义行为这样的前pression结果指向的值。声明的char *一=东西; 只是存储指向字符串的变量(不安全,因为它是虚掷常量修改)。在字符2个[] =东西; 是完全不同的。它实际上是声明数组并初始化它,就像 int类型的[] = {1,2,3}; 。这里引号的字符串是初始化前pression。

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.

这篇关于分割故障原因在Linux字符数组和指针用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆