1

以下代码在编译期间产生分段错误:

(gdb) 运行
启动程序:/home/anna/Desktop/a.out
程序收到信号 SIGSEGV,分段错误。
/lib/i386-linux-gnu/libc.so.6 中的 strtok() 中的 0xb7e97845

#include <string.h>
#include <stdio.h>

main () {
char * sentence = "This is a sentence.";
char * words[200] ;
words[0] = strtok(sentence," ");
}

更改第 5 行后,没有抛出错误。

#include <string.h>
#include <stdio.h>

main () {
char  sentence[] = "This is a sentence.";
char * words[200] ;
words[0] = strtok(sentence," ");
}

为什么会这样?

4

2 回答 2

6
char * sentence = "This is a sentence.";

sentence是指向字符串文字“这是一个句子”的指针。存储在只读存储器中,您不应对其进行修改。
以任何方式修改字符串文字都会导致未定义的行为,在您的情况下,它会表现为分段错误。

好读:
char a[] = ?string?; 之间有什么区别?和 char *p = ?string?;?

于 2012-12-20T11:39:29.433 回答
2

阅读(BUGS部分)的man页面,strtok

  • 这些函数修改它们的第一个参数。
  • 这些函数不能用于常量字符串。

并且char *sentence = "This is a sentence";在只读上下文中分配,因此被视为常量。

于 2012-12-20T12:02:08.503 回答