简体   繁体   中英

strtok() in c - segmentation fault

Everytime I try to use strtok() i get an segmentation fault. Don't know why- I'm new to C.

Here is my code:

#include "shellutils.h"
#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    char input[150];

    while(1) {
        prompt();
        fgets(input, 150, stdin);

        char *fst_tkn = strtok(input, " ");

        printf("%s", fst_tkn);


        if(feof(stdin) != 0 || input == NULL) {
            printf("Auf Bald!\n");
            exit(3);
        }
    }
}

Thanks for your help!

With regards to the code:

char *fst_tkn = strtok(input, " ");
printf("%s", fst_tkn);

If your input variable is empty, or contains only spaces, then fst_tkn will be set to NULL . Then, when you try and print that as a string, all bets are off.

You can see that in the following code by adjusting the values tou give to input :

#include <stdio.h>
#include <string.h>
int main (void) {
    char input[] = "";
    char *fst_tkn = strtok (input, " ");
    printf ("fst_tkn is %s\n", (fst_tkn == NULL) ? "<<null>>" : fst_tkn);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM