Question

c++ function, strtok() cplusplus.com

Will this example suffer from buffer overrun if str is not terminated properly?

/* strtok example */
/* source - cplusplus.com (see link below) */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-"); // walk the stack?
  }
  return 0;
}

If str isn't terminated correctly with "\0", isn't it possible for

pch = strtok (NULL, " ,.-");

to walk the stack?

Thanks!

Was it helpful?

Solution

Most string-handling functions will walk off the end if the string is not null-terminated.

However, in your code example, str is terminated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top