...
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" */ |
...
In this compliant solution, the string being tokenized is copied into a temporary buffer which is not referenced after the 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" */ |
...