c - c 中的 strtok() - 段错误

标签 c segmentation-fault strtok

每次我尝试使用 strtok() 时,我都会遇到段错误。不知道为什么-我是 C 的新手。

这是我的代码:

#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);
        }
    }
}

感谢您的帮助!

最佳答案

关于代码:

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

如果您的 input 变量为空,或仅包含空格,则 fst_tkn 将设置为 NULL。然后,当您尝试将其打印为字符串时,所有的赌注都没有了。

您可以通过调整给 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;
}

关于c - c 中的 strtok() - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554102/

相关文章:

c - 如何修复错误消息 "__builtin_avr_delay_cycles expects a compile time integer constant make"?

c - 用 strtok() 分割字符串会出错

c - strtok 未按预期工作,未拆分字符串

c++ - 段错误/使用大小为 8 的未初始化值

c - 分段故障核心转储: Function that returns the next prime number

c - 将 strtok 存储在数组中 ~ C

c - 如何正确使用malloc和strtok?

用 C 单击网页上的按钮

多线程程序中的核心转储

c - 带有指针的 C 错误中的 Malloc 函数