Problem with strtok and segmentation fault

后端 未结 2 995
眼角桃花
眼角桃花 2020-12-20 20:26

I have two helper functions to break up strings in the format of decimal prices ie. \"23.00\", \"2.30\"

Consider this:

char price[4] = \"2.20\";

            


        
2条回答
  •  爱一瞬间的悲伤
    2020-12-20 20:30

    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).

提交回复
热议问题