-2
#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.
}
上記のスニペットでは、私は区切り文字としてwhitspace上の文字列をトークン化しようとしています。 newline(press ENTER)
またはa sequence of whitespaces
のように入力すると、strtok()
が呼び出されます。私が理解しているところでは、それは後で健全性チェックで扱うべきであるNULL
を返すべきですが、それは本当に起こっていません。空文字列のstrtok()セグメンテーションフォルトの入力
ここで私は何が分からないのですか?
['malloc()'と 'C 'の返り値をキャストしない理由については、このディスカッションを参照してください。](http://stackoverflow.com/q/605845/2173917)。 –
'malloc()'がどのように成功したのですか? –
あなたは[___MCVE___](http://stackoverflow.com/help/mcve)の作成を気にしますか? –