Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFCCCC
char string[] = "Hello secure coding wiki!";
char *token;

token = strtok(string, ' ');
puts(token);

while ( token = strtok(NULL, ' ') ) {
  puts(token);
}

/* string  has been modified */

Wiki Markup
In this example, the {{strtok()}} function is used to parse the first argument into space-delimited tokens; it will output each word from the string on a new line. However, after the while loop ends, string\[\] will have been modified to look like this: {{"Hello\0secure\0coding\0wiki\0"}}. Any further manipulation of {{string}} operating on the assumption that it is still whole will see only "Hello" instead of the expected string value.

Compliant Solutions

One possible solution is to copy the string being tokenized into a temporary buffer which isn't referenced after the calls to strtok():

Code Block
bgColor#ccccff
    char string[] = "Hello secure coding wiki!";
    char buff[256];
    char *token;

    strncpy(buff, string);
    token = strtok(buff, ' ');
    printf("%s\n", token);

    while ( token = strtok(NULL, ' ') ) {
        printf("%s\n", token);
    }

    /* further string manipulation on string[] succeeds */

...

References

Unix Man page strtok(3) Library functions which enter the namespace from linked-in libraries can have the same name as a #declare'd macro; in order to prevent such a naming conflict parenthesize the name of the library function when it is called: