Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c strtok returns NULL after return from recursion

When i'm not calling the same function in my code everything works well but when the function returns from a recursion suddenly the variable pch is NULL:

 void someFunction()
     {
        char * pch;
        char tempDependencies[100*64+100];
        strcpy(tempDependencies,map[j].filesNeeded);
        pch = strtok(tempDependencies,",");
        while (pch != NULL)
        {
            someFunction(); <- if i comment this out it works fine
            pch = strtok (NULL, ",");
        }
      }

So for instance when the loop acts on the string file2,file3,file4 it correctly split file2 and modifies the string to file2\\000file3,file4 but the next call to pch = strtok (NULL, ","); renders pch to be 0x0. Are there things that i'm not aware of when calling recursion?

like image 421
Tom Avatar asked Nov 14 '12 06:11

Tom


2 Answers

strtok() is not reentrant. If you want use it in a recursive function you must use strtok_r().

See also: strtok, strtok_r

like image 70
Olaf Dietsche Avatar answered Sep 21 '22 06:09

Olaf Dietsche


You can't call the strtok function again before the previous execution is done - It is not reentrant.

Use its reentrant version strtok_r instead.

like image 43
codaddict Avatar answered Sep 24 '22 06:09

codaddict