Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of string returned by strtok()

Tags:

c

I want to find length of word from string. When i use strlen(split) out of while loop it's ok. But when i use it from loop i have segmentation fault error. What's the problem?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char string[] = "Hello world!";
    char* word = strtok(string, " ");
    printf("%d\n", strlen(word));
    while(split != NULL) {
        word = strtok(NULL, " ");
        printf("%d\n", strlen(word ));
    }
}
like image 329
user3021370 Avatar asked Oct 24 '25 23:10

user3021370


1 Answers

You need to check that strtok didn't return NULL before calling strlen

From the strtok man page (my emphasis)

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.

while(word != NULL) {
    word = strtok(NULL, " ");
    if (word != NULL) {
        printf("%d\n", strlen(word ));
    }
}

Note that there was also a typo in your code. The while loop should test word rather than split.

like image 78
simonc Avatar answered Oct 26 '25 13:10

simonc