Reputation: 123
I have to get the third word in a string and wanted to use strtok. Now, the first printf works but after that I get a Seg Fault. So tokenizedString = strtok(NULL, " ");
must be causing the issue, right?
Just for context: I'm looking for the third word in a string and there can be as many spaces as possible between the words.
#include <string.h>
#include <stdio.h>
char *tokenizeString(char *userCommand)
{
char *tokenizedString;
int counterForToken;
tokenizedString = strtok(userCommand, " ");
for(counterForToken = 0; counterForToken != 3; counterForToken++)
{
printf("%s\n", tokenizedString);
tokenizedString = strtok(NULL, " ");
if(tokenizedString == NULL)
{
break;
}
}
printf("%s\n", tokenizedString);
return tokenizedString;
}
int main(void)
{
char userCommand[255] = {0};
fgets(userCommand, sizeof(userCommand), stdin);
tokenizeString(userCommand);
}
Upvotes: 0
Views: 141
Reputation: 170074
Now, the first printf works but after that I get a Seg Fault. So
tokenizedString = strtok(NULL, " ");
must be causing the issue, right?
No, that is very poor correlation. The issue is in fact in the second call to printf
. You can pass it tokenizedString
when tokenizedString == NULL
. The format specified %s
is specified to expect a valid pointer to the first character of a zero terminated array of characters. Passing it NULL
is illegal and leads to undefined behavior (causing a crash for instance). The fix is simple: check for a null pointer value. And the same applies to the first iteration of the loop, of course
char *tokenizeString(char *userCommand)
{
char *tokenizedString;
int counterForToken;
tokenizedString = strtok(userCommand, " ");
for(counterForToken = 0; counterForToken != 3 && tokenizedString != NULL; counterForToken++)
{
printf("%s\n", tokenizedString);
tokenizedString = strtok(NULL, " ");
}
if(tokenizedString != NULL)
printf("%s\n", tokenizedString);
return tokenizedString;
}
Upvotes: 1