On my system, the following program:
int main(){
char *strgptr;
char buf[5] = {'b','a','a','a','\0'};
char *tmp = strtok_r(buf, ".", &strgptr);
if(tmp != NULL){
printf("Found a . in baaa?\n");
printf("It was found starting at: %s\n", tmp);
}
else
printf("Everything is working.\n");
}
prints:
Found a . in baaa?
It was found starting at: baaa
However, if I swap the “.” delimiter string in strtok_r for “a”, I get (as expected):
Found a . in baaa?
It was found starting at: b
But swapping the “.” for any other char not appearing in buf (e.g. “c”) produces:
Found a . in baaa?
It was found starting at: baaa
The man page for strtok_r, as expected, says:
The strtok() and strtok_r() functions return a pointer to the next token,
or NULL if there are no more tokens.
So why does strtok_r fail to return NULL when passed a string which contains none of the tokens in question?
Because the delimiter isn’t found, so you’re getting the whole string returned. It acts as if there’s an invisible delimiter after the string.