tags:

views:

53

answers:

1

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!

+1  A: 

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

However, in your code example, str is terminated.

Oli Charlesworth
Roger that. My example shows it, but if I was using a function without string termination, a buffer overrun could happen.thanks!
Kevin