【发布时间】: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,我应该稍后在健全性检查中处理它,但这并没有真正发生。
请帮帮我,我在这里缺少什么?
【问题讨论】:
-
你怎么知道你的
malloc()是成功的? -
你介意创建一个MCVE吗?
-
无法复制:ideone.com/YoSTm6
-
或者您是否尝试使用
token的值而不检查它是否为NULL?
标签: c segmentation-fault strtok