以下代码在编译期间产生分段错误:
(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," ");
}
为什么会这样?
2 回答
阅读
strtok
的man
页(BUGS部分),这些函数修改了它们的第一个参数 .
这些函数不能用于常量字符串 .
和
char *sentence = "This is a sentence";
在只读上下文中分配,因此视为包含 .sentence
是指向字符串文字的指针"This is a sentence."存储在只读存储器中,您不应该修改它 .以任何方式修改字符串文字会导致 Undefined Behavior ,在您的情况下,它会出现分段错误 .
Good Read:
What is the difference between char a[] = ?string?; and char *p = ?string?;?