【问题标题】:strtok() segmentation fault on empty string input空字符串输入上的 strtok() 分段错误
【发布时间】:2016-09-09 17:10:03
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INPUT_LENGTH 1024

char *readline(FILE* fp, int max_length)
{
    //The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    int len = 0;
    int current_max = max_length;

    str = (char*)malloc(sizeof(char)*current_max);
    if(!str)
        return str;

    while((ch = fgetc(fp))!=EOF)
    {
        /* Separate newline handling from EOF handling */
        if((char)ch == '\n')
        {
            str[len] = '\0';
            return str;
        }
        str[len++] = ch;

        if(len == current_max)
        {
            current_max = current_max + max_length;
            str = realloc(str, sizeof(char)*current_max);
            if(!str)
                return str;
        }
    }
    str[len] = '\0';

    return str;
}


int main(void)
{
    char *input, *token;

    input = readline(stdin, MAX_INPUT_LENGTH);

    printf("BEFORE\n");
    token = strtok(input, " "); //Segmentation Fault Here
    printf("AFTER"); //control never reaches here on " " or "\n" input.
}

在上面的 sn-p 中,我试图将 whitspace 上的字符串标记为分隔符。每当我以newline(press ENTER)a sequence of whitespaces 的形式提供输入时,strtok() 就会调用段错误。据我了解,它应该返回NULL,我应该稍后在健全性检查中处理它,但这并没有真正发生。

请帮帮我,我在这里缺少什么?

【问题讨论】:

标签: c segmentation-fault strtok


【解决方案1】:

您对故障发生位置的分析不正确

printf("AFTER"); //control never reaches here on " " or "\n" input.

实际上,控制确实到达了那里。您只是看不到“AFTER”消息,因为那里没有换行符或刷新。把代码改成这样,谜底就会消失:

printf("AFTER\n");

我敢打赌你不能用你的 MCVE 复制错误,因为它确实到达了main 的末尾,它会刷新输出。您忘记了 MCVE 中的“V”。您需要验证它是否复制了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多