...
Compliant Solution
In this compliant solution the string being tokenized is copied into a temporary buffer which is not referenced after the calls call to strtok()
:
Code Block | ||
---|---|---|
| ||
char *token; const char *path = getenv("PATH"); /* PATH is something like "/usr/bin:/bin:/usr/sbin:/sbin" */ char *copy = (char *)malloc(strlen(path) + 1); if (copy == NULL) { /* handle error */ } strcpy(copy, path); token = strtok(copy, ":"); puts(token); while (token = strtok(0, ":")) { puts(token); } free(copy); copy = NULL; printf("PATH: %s\n", path); /* PATH is still "/usr/bin:/bin:/usr/sbin:/sbin" */ |
...
Never use this function. This function modifies its first argument. The identity of the delimiting character is lost. This function cannot be used on constant strings.
Improper The improper use of strtok()
use is likely to result in truncated data, producing unexpected results later in program execution.
...