C String split and print the tokens.

前端 未结 2 1098

I am trying to split the string and print the tokens.

int main()
{
    char line[255] = \"182930101223, KLA1513\";
    char val1[16];
    char val2[7];

    str         


        
2条回答
  •  太阳男子
    2021-01-23 08:03

    OK, I thought this was an unrelated issue, but I now think it is the issue you are seeing.

    It's important to remember that C strings take 1 extra character than they contain. This is the terminating NUL character (\0), and marks the end of the text.

    So KLA1513 is actually 8 characters (KLA1513\0). Additionally, because you are not trimming spaces, it is 9 characters! _KLA1513\0 (_ is a space).

    That means that you're overrunning the memory in your second strcpy, leading to undefined behaviour, which (you will come to realise) is your worst nightmare.

    When you print it, who knows what state the program is in. Maybe the memory you overwrote was part of the print call, or maybe it was overwritten again and now var2 isn't terminated.

    Just make var2 bigger (9 characters is enough here), and in future, use the safe forms (strncpy, for example). Mistakes like this are how hackers usually manage to compromise systems.

提交回复
热议问题