简体   繁体   English

strtok()在c-分段错误

[英]strtok() in c - segmentation fault

Everytime I try to use strtok() i get an segmentation fault. 每当我尝试使用strtok()时,都会出现分段错误。 Don't know why- I'm new to C. 不知道为什么-我是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 . 如果input变量为空或仅包含空格,则fst_tkn将设置为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 : 您可以通过调整tou给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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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