相关疑难解决方法(0)

Linux上C字符串和指针的分段故障

所以我有以下程序:

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

它在"one [1] ='b'"这一行上有段错误,因为指针"one"所指向的内存必须位于只读内存中.然而,问题是为什么"2 [1] ='b'"行不是段错误?查看gcc的程序集输出:

.file   "one.c"
        .section        .rodata
.LC0:
        .string "computer"
.LC1:
        .string "another"
        .text
.globl main
        .type   main, @function
main:
Run Code Online (Sandbox Code Playgroud)

我们看到两个字符串都在rodata部分,因此它们是只读的.那么为什么"两个[1] ='b'这一行不会出现段错误?

c c++ linux elf segmentation-fault

15
推荐指数
1
解决办法
5437
查看次数

标签 统计

c ×1

c++ ×1

elf ×1

linux ×1

segmentation-fault ×1