strtok() - 分段错误 [英] strtok() - Segmentation Fault
问题描述
可能的重复:
strtok 给出分段错误
我尝试使用 strtok 函数将字符串拆分为多个标记,但在此示例中它返回一个 seg.故障错误.我哪里错了??
#include #include int main(int argc, char** argv){int i=0;char * string = "HI:HOW:ARE:YOU:?", *tmp;而(1){if(i==0) tmp=strtok(string,":");否则 tmp=strtok(NULL,":");if(tmp==NULL) 中断;printf("%s\n",tmp);我++;}返回 1;}
更改
char * string = "HI:HOW:ARE:YOU:?"
为了
char string [] = "HI:HOW:ARE:YOU:?"
用 char string [] 你有一个数组,而 char * 你有一个指针.当你声明一个数组时,它会请求空间来分配你的字符串的大小.char * 字符串创建一个指向文字字符串的指针.
char *string 的问题在于不应更改该点,因为字符串文字通常存储在只读内存中,从而导致 未定义行为 33
(有关更多详细信息,请阅读此 https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals )>
因此,由于使用 strtok 修改了字符串的内容并将其分解为更小的字符串(标记),因此您会遇到问题.
Possible Duplicate:
strtok giving Segmentation Fault
I try to use strtok function to split string in many tokens but in this example it returns me a seg. fault error. Where i'm in wrong??
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv){
int i=0;
char * string = "HI:HOW:ARE:YOU:?", *tmp;
while(1){
if(i==0) tmp=strtok(string,":");
else tmp=strtok(NULL,":");
if(tmp==NULL) break;
printf("%s\n",tmp);
i++;
}
return 1;
}
Change
char * string = "HI:HOW:ARE:YOU:?"
for
char string [] = "HI:HOW:ARE:YOU:?"
With char string [] you have an array, and char * you have a pointer. When you declare an array, it will request space to allocate the size of your string. The char * string creates a pointer that points to a literal string.
The problem with char *string it is that the point should not be changed because string literals are typically stored in read-only memory, thus causing undefined behavior 33
( for more detail read this https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals )
Therefore, since with strtok the contents of the string is modified and broken into smaller strings (tokens) you got problems.
这篇关于strtok() - 分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!