Why strtok()
is a bad idea
Do not use strtok()
in normal code, strtok()
uses static
variables which have some problems. There are some use cases on embedded microcontrollers where static
variables make sense but avoid them in most other cases. strtok()
behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok()
.
Consider this example:
#include <stdio.h>
#include <string.h>
//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
char *p = strtok(input, "/");
while(p)
{
printf("%s, ",p);
p = strtok(NULL, "/");
}
}
int main(void)
{
char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
char *p = strtok(buffer, ":");
while(p)
{
printContent(p);
puts(""); //print newline
p = strtok(NULL, ":");
}
return 0;
}
You may expect the output:
abc, def, ghi,
ABC, DEF, GHI,
But you will get
abc, def, ghi,
This is because you call strtok()
in printContent()
resetting the internal state of strtok()
generated in main()
. After returning, the content of strtok()
is empty and the next call to strtok()
returns NULL
.
What you should do instead
You could use strtok_r()
when you use a POSIX system, this versions does not need static
variables. If your library does not provide strtok_r()
you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.