...
In this example, the strtok()
function is used to parse the first argument into colon-delimited tokens; it outputs each word from the string on a new line. Assume that PATH
is "/usr/bin:/usr/sbin:/sbin"
.
Code Block | ||
---|---|---|
| ||
char *token; char *path = getenv("PATH"); token = strtok(path, ":"); puts(token); while (token = strtok(0, ":")) { puts(token); } printf("PATH: %s\n", path); /* PATH is now just "/usr/bin" */ |
However, after After the loop ends, path
will have been modified to look like this is modified as follows: "/usr/bin\0/bin\0/usr/sbin\0/sbin\0"
. This is an issue on several levels. The because the local path
variable becomes /usr/bin
. Even worse, and because the environment variable PATH
has been unintentionally changed, which could cause have unintended resultsconsequences.
Compliant Solution
In this solution the string being tokenized is copied into a temporary buffer which is not referenced after the calls to strtok()
:
...