Strtok () Prototype:
char * strtok (char *s, const char *delim);
Function Description: Strtok () is used to split a string into fragments. The parameter S points to the string to be split, the parameter Delim is the split string, and when Strtok () discovers the split character of the parameter Delim in the string of the parameter s, the character is changed to the \ = character . at the first call, Strtok () must give the parameter S string, and the subsequent call sets the parameter s to null. Each successful call returns the next segmented string pointer.
Return value: Returns the next segmented string pointer, or null if no partition has been made.
Problem:
1. " changeto": Strtok () modifies the source string, so it is best to re-copy it when used.
2, " at the first call, Strtok () must give the parameter S string, the next call will set the parameter s to null": The subsequent call sets the parameter s to null It is because the first invocation of the cut string exists in the static variable of the function, and passing in null means using the data in the static variable. Therefore, if there are two or more functions in the program call stack or multiple threads calling Strtok () at the same time, the problem occurs.
Examples of multiple function calls:
Func1 (.. )
{
...
TMP = Strtok (str, delim);
while (Strtok (NULL, Delim))
{
...
}
...
}
Func ()
{
...
TMP = Strtok (str, delim);
while (Strtok (NULL, Delim))
{
...
Func1 ();
...
}
...
}
Func () error due to change of static variable value in Strtok () in func1 ();
Workaround: Use Strtok_r ()
function prototypes are char *strtok_r (char *str, const char *delim, char * *saveptr);
Strtok_r is actually the this pointer that implicitly holds the strtok internally, interacting with the outside of the function as arguments. Passed, saved, or even modified by the caller. Requires the caller to continuously slice the homologous string, in addition to assigning the STR parameter to NULL, and also passing the saveptr saved at the last shard.
Linux Strtock () function usage issues