为什么 strtol 和 strtok 的这种组合不起作用?
谁能告诉我这段代码有什么问题吗?
for(int i=0;i<4;i++)
{
long int a = strtol(strtok("1-2-3-4","-"),(char**)NULL,10);
cout << a <<endl
}
我在 Solaris Unix 上运行。它给了我一个分段错误。
错误出在 strtol()
中。
Could anyone tell me what is wrong with this code?
for(int i=0;i<4;i++)
{
long int a = strtol(strtok("1-2-3-4","-"),(char**)NULL,10);
cout << a <<endl
}
I'm running on Solaris Unix. It's giving me a segmentation fault.
The fault is in strtol()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
错误是由
strtok
调用引起的,而不是由strtol
引起的。您不能对字符串文字调用strtok
,因为它将尝试修改字符串。修改字符串文字会导致 C++ 中出现未定义的行为。The error is with the
strtok
call, not withstrtol
. You can't callstrtok
on a string literal, since it's going to try to modify the string. Modifying a string literal causes undefined behaviour in C++.问题有很多。
我期望核心转储是因为字符串
"1-2-3-4"
存储在只读内存中,因此当strtok()
修改它时(隔离第一个令牌),程序崩溃。你说崩溃发生在strtol()
;这表明strtok()
的返回值为 NULL。第一次调用
strtok()
使用字符串作为参数;第二个调用在其位置传递 NULL 以指示“从上次停止的地方继续”。正如所写,如果字符串是可修改的,那么您将解析1
四次。这更接近正确(尽管未经测试):
通常,您需要从
strtol()
进行错误检测;此外,这样做是相当令人担忧的。但是,有了示例字符串,您就不必担心这一点。The problems are legion.
I would expect that the core dump is because the string
"1-2-3-4"
is stored in read-only memory, so whenstrtok()
modifies it (to isolate the first token), the program crashes. You say the crash is instrtol()
; that would suggest that the return value fromstrtok()
is NULL.The first call to
strtok()
uses the string as an argument; the second call passes NULL in its place to indicate 'continue where you left off last time'. As written, if the string was modifiable, then you'd parse1
four times.This is closer to correct (though untested):
In general, you need to do error detection from
strtol()
; further, doing so is quite fraught. However, with the sample string, you would not have to worry about that.由于问题已经讨论过,我想展示一种替代方法:
As the problem is already discussed, I'd like to show an alternate approach :