The strtok
library strtok
uses the internal static state for the current parsing position:
- when called with strings, it starts a new parsing,
- when called with
NULL
, it uses its internal state as the first argument.
If you directly or indirectly call strtok
from the analysis loop, the internal state will be updated, and a call with NULL
from the external region will not continue from the previous state, it may cause undefined behavior.
The Posix strtok_r
function takes an explicit state argument, so it can be used in nested contexts. If this function is available on your system, use it in all places where you use strtok
. Alternatively, you can use another method with strchr()
or strcspn()
.
strtok_r
standardized in Posix. Depending on your target system, it may or may not be available. MacOS and most Unix systems are Posix compatible. Windows may have this name under a different name. If it is not available, you can override it in your program and conditionally compile it.
Here is a simple implementation that you use:
char *strtok_r(char *s, const char *delim, char **context) { char *token = NULL; if (s == NULL) s = *context; s += strspn(s, delim); if (*s != '\0') { token = s; s += strcspn(s, delim); if (*s != '\0') { *s++ = '\0'; } } *context = s; return token; }
source share