Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String parsing in C using strtok

I've got this little source code, made for testing the parsing of a string similar to variable string I need to use in other project

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main (void)
{
    char string[] = "C-AC-2C-3C-BOB";
    char* s;
    char* hand[3];
    char* usr;


    s = (char*) calloc(1, sizeof(char));
    hand[1] = (char*) calloc(3, sizeof(char));
    hand[2] = (char*) calloc(3, sizeof(char));
    hand[3] = (char*) calloc(3, sizeof(char));
    usr = (char*) calloc(21, sizeof(char));

    s = strtok (string,"-");
    hand[1] = strtok (NULL, "-");
    hand[2] = strtok (NULL, "-");
    hand[3] = strtok (NULL, "-");
    usr = strtok (NULL, "\0");

    printf("%s:%s:%s:%s:%s\n", s, hand[1], hand[2], hand[3], usr);

    return 0;
}

The problem is that i got these 3C:AC:2C:3C:BOB as result of printf instead of C:AC:2C:3C:BOB.

-------EDIT-----

Code without memory leaks. Problem remains

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main (void)
{
    char string[] = "C-AC-2C-3C-BOB";
    char* s;
    char* hand[3];
    char* usr;

    s = strtok (string,"-");
    hand[1] = strtok (NULL, "-");
    hand[2] = strtok (NULL, "-");
    hand[3] = strtok (NULL, "-");
    usr = strtok (NULL, "\0");

    printf("%s:%s:%s:%s:%s\n", s, hand[1], hand[2], hand[3], usr);

    return 0;
}
like image 975
Arrigo Pierotti Avatar asked Dec 12 '22 12:12

Arrigo Pierotti


1 Answers

You declare an array hand as having three entries, then you index it using indexes 1 through 3. But arrays in C have indexes from 0 to size-1 (e.g. 2 in your case).

So you write/read to/from out of bounds of the array, leading to undefined behavior.

Change the indexes of your array to 0 through 2 and it should work fine.

like image 191
Some programmer dude Avatar answered Dec 26 '22 14:12

Some programmer dude