[英]In C, strtok causes segmentation fault
I'm new to C. 我是C的新手。
I'm trying to eliminate ".,;?!" 我正在尝试消除“。,;?!” from a string using strtok and then to create a simple string without any punctuation marks, but it gives me a 'Segmentation fault' after compilation.
使用strtok从字符串中创建字符串,然后创建一个没有任何标点符号的简单字符串,但是编译后出现了“分段错误”。 Why and how to fix it ?
为什么以及如何解决?
char simple_s[100];
char delim[20];
memset(simple_s,0,100);
memset(delim,0,100);
strcpy(delim,strtok(s,",.;:!? "));
while(delim != NULL) {
strcat(simple_s,delim);
strcpy(delim,strtok(NULL,",.;:!? "));
}
printf("%s",simple_s);
There are several errors in the code. 代码中有几个错误。 First you zero too many bytes with
首先,您将太多字节清零
char delim[20];
memset(delim,0,100);
To avoid this error, you should use 为避免此错误,您应该使用
char simple_s[100];
char delim[20];
memset(simple_s,0,sizeof(simple_s));
memset(delim,0,sizeof(delim));
Next, you have used the return value of strtok()
before checking if it is NULL
接下来,在检查它是否为
NULL
之前,已使用strtok()
的返回值。
strcpy(delim,strtok(s,",.;:!? "));
and from there you go on to test delim
for being NULL
instead of checking for a NULL
pointer from strtok()
然后从那里继续测试
delim
是否为NULL
而不是从strtok()
检查NULL
指针
while(delim != NULL) {
strcat(simple_s,delim);
strcpy(delim,strtok(NULL,",.;:!? ")); // <--- copying from NULL pointer
}
but delim
is not even necessary, you need to work with the pointer returned by strtok()
. 但是
delim
甚至不是必需的,您需要使用strtok()
返回的指针。 Putting this back together, I would have 放回去,我会
char simple_s[100] = ""; // initialise string
char seps[] = ",.;:!? "; // added separators, so not to duplicate
char *tok; // added to receive value from strtok()
tok = strtok(s, seps);
while(tok) { // until `NULL` returned
strcat(simple_s, tok);
tok = strtok(NULL, seps);
}
printf("%s",simple_s);
Additionally, I have skipped over the string length checking. 另外,我跳过了字符串长度检查。 When you have it working, check that the new length of
simple_s[]
won't break, before you strcat()
the next substring. 当它起作用时,请在
strcat()
下一个子字符串之前检查simple_s[]
的新长度是否不会中断。
delim must be defined as a char *. delim必须定义为char *。 Here is your code with a couple of bugs fixed:
这是您的代码,已修复了两个错误:
#include <stdio.h>
#include <string.h>
#include <strings.h>
int main(int argc, char **argv)
{
char s[100];
char simple_s[100];
char *delim;
strcpy(s, "abc,def");
memset(simple_s,0,sizeof(simple_s));
delim = strtok(s,",.;:!? ");
while(delim != NULL) {
strcat(simple_s,delim);
delim = strtok(NULL,",.;:!? ");
}
printf("%s",simple_s);
return 0;
}
This outputs abcdef
输出
abcdef
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.