Search code examples
cstringsplitstrtok

Splitting strings in C strtok()


I want to split strings received from the terminal input, if they are contained on a buffer. If they are I want to print them.

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

char* fich[5]={"ha","he","hi","ho","hu"};

int main(){

char passaarg[70];
const char space[2]= " ";
char *token;
int i;

while(1){

    read(STDIN_FILENO, passaarg, 70);
    for (i = 0; i < 5; i++){
        if(strncmp(passaarg, fich[i], 2) == 0){
            token = strtok(passaarg, space);
            while(token != NULL){
                printf("%s\n", token);
                token = strtok(NULL, space);
                printf("%s\n", token);
            }
            break;
        }
    }
}
return 0;
}

My output is the following one:

ha he
ha
he

he

Segmentation fault (core dumped)

Solution

  • I suspect your problem is here:

    token = strtok(passaarg, space);
    while(token != NULL){
        printf("%s\n", token);
        token = strtok(NULL, space);
        printf("%s\n", token);
    }
    

    That second printf will cause undefined behavior (likely a crash) when strtok returns NULL, as it will when there are no more tokens in the string. Just remove that line.

    Stylistically, I'd use a for loop here:

    for(token = strtok(passaarg, space); token != NULL; token = strtok(NULL, space)) {
        printf("%s\n", token);
    }