为什么 strtok 会导致分段错误? [英] Why is strtok causing a segmentation fault?

查看:81
本文介绍了为什么 strtok 会导致分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码给了 Seg.最后一行有问题?

Why does the below code give Seg. Fault at last line?

char* m=ReadName();
printf("\nRead String %s\n",m); // Writes OK
char* token;
token=strtok(m,'-');

如前所述,读取字符串打印没有问题,但为什么不能拆分为令牌?

As said, read string prints w/o problem, but why cannot split to tokens?

推荐答案

strtok 修改它的第一个参数,因此它应该是可修改的.

strtok modifies its first argument, hence it should be modifiable.

也许 ReadName() 返回一个指向只读字符数组的指针.你能告诉我们你的 ReadName() 函数吗.

Maybe ReadName() returns a pointer to a read-only char array.Can you show us your ReadName() function.

如果这就是段错误的原因,您可以在使用 strdup 函数如:

If that is the reason for seg-faullt, you can create a copy of the char array before you pass it to strtok using the strdup function like:

char *copy = strdup(m);
token = strtok(copy,'-');
....
....
free(copy); // free the copy once you are done using it.

这篇关于为什么 strtok 会导致分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆