[英]strtok segmentation fault error in C
I know this question is frequently asked but none of other questions are helpful. 我知道这个问题经常被问到,但是其他问题都没有帮助。 I have a code
我有一个密码
char *hamlet[] = {"Give every man thy ear, but few thy voice.",
"Neither a borrower nor a lender be.",
"For loan oft loses both itself and friend",
"And borrowing dulls the edge of husbandry.",
"This above all: to thine own self be true."};
int i;
for (i = 0; i < NUM_SENTENCES; i++) {
int size;
char **words = splitString(hamlet[i], &size);
and in another .c file I have 在另一个.c文件中
char** splitString(char theString[], int *arraySize){
int numWords = 1;
int i=0;
numWords += countSpaces(theString);
char **wordArray = malloc(numWords * sizeof(char*));
char *token;
token = strtok(theString, " ");
return wordArray;
Problem is, I always get segmentation fault when I link them and run it. 问题是,当我链接它们并运行它时,我总是会遇到分段错误。 I believe this is error caused by memory since first code and second code are located in different .c files.
我相信这是内存引起的错误,因为第一代码和第二代码位于不同的.c文件中。 I can't really find a way to solve it
我真的找不到解决方法
The contents of the hamlet
array are all string literals. hamlet
数组的内容都是字符串文字。 These are not modifiable and typically resided in a read-only section of memory. 这些是不可修改的,通常驻留在内存的只读部分中。 The
strtok
function modifies its argument, so that's why you get a crash. strtok
函数会修改其参数,因此这就是崩溃的原因。
You need to make a copy of the string you're working on using strdup
. 您需要使用
strdup
复制正在处理的字符串。 Then you can copy out the substrings. 然后,您可以复制出子字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.