Problem with strtok and segmentation fault

巧了我就是萌 提交于 2019-11-29 14:03:13

Because strtok() modifies the input string, you run into problems when it fails to find the delimiter in the getCents() function after you call getDollars().

Note that strtok() returns a null pointer when it fails to find the delimiter. Your code does not check that strtok() found what it was looking for - which is always risky.


Your update to the question demonstrates that you have learned about at least some of the perils (evils?) of strtok(). However, I would suggest that a better solution would use just strchr().

First, we can observe that atoi() will stop converting at the '.' anyway, so we can simplify getDollars() to:

unsigned getDollars(const char *price)
{
    return(atoi(price));
}

We can use strchr() - which does not modify the string - to find the '.' and then process the text after it:

unsigned getCents(const char *price)
{
    const char *dot = strchr(price, '.');
    return((dot == 0) ? 0 : atoi(dot+1));
}

Quite a lot simpler, I think.


One more gotcha: suppose the string is 26.6; you are going to have to work harder than the revised getCents() just above does to get that to return 60 instead of 6. Also, given 26.650, it will return 650, not 65.

This:

char price[4] = "2.20";

leaves out the nul terminator on price. I think you want this:

char price[5] = "2.20";

or better:

char price[] = "2.20";

So, you will run off the end of the buffer the second time you try to get a token out of price. You're just getting lucky that getCents() doesn't segfault every time you run it.

And you should almost always make a copy of a string before using strtok on it (to avoid the problem that Jonathan Leffler pointed out).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!