using the code demonstrated below, the program crashes. It is a code I copy-pasted from this source and haven't modified it at all, yet strtok seems to cause the program to crash.
#include <string.h>
#include <stdio.h>
int main()
{
char str[80] = "This is - www.tutorialspoint.com - website";
const char s[2] = "-";
char *token;
/* get the first token */
token = strtok(str, s);
/* walk through other tokens */
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
return(0);
}
I can't seem to find the cause for this. I've tried looking for a source to the strtok function, and came across this:
char * __cdecl strtok(char *s1, const char *delimit)
{
static char *lastToken = NULL; /* UNSAFE SHARED STATE! */
char *tmp;
/* Skip leading delimiters if new string. */
if ( s1 == NULL ) {
s1 = lastToken;
if (s1 == NULL) /* End of story? */
return NULL;
} else {
s1 += strspn(s1, delimit);
}
/* Find end of segment */
tmp = strpbrk(s1, delimit);
if (tmp) {
/* Found another delimiter, split string and save state. */
*tmp = '\0'; //->This seems to be the line at fault<-
lastToken = tmp + 1;
} else {
/* Last segment, remember that. */
lastToken = NULL;
}
return s1;
}
Making a local copy and using it instead in my code resulted with the same issue, and after using a few prints it seems that after the first call to the function, it crashes, specifically, strpbrk returns the correct value, which can be accessed (By using a printf to it's return value), but when assigned the value \0 it causes the program to crash (apparent by being unable to print any message entered after it).
That's as far as I can get, does anybody have any idea what's going on?
Thanks in advance for your replies.