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 */

...

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

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

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

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

Another possibility is to provide your own implementation of strtok() which does not modify the initial arguments.

To quote the Linux Programmer's Manual (man) page on strtok(3):

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.

References

C99 Section 7.21.5.8, "The strtok function"
Unix Man page strtok(3)