-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()
호출은 segfaults입니다. 내가 이해하는 것으로부터, 나중에 성의 검사에서 처리해야하는 NULL
을 반환해야하지만 실제로 일어나지는 않습니다.빈 문자열 입력에 대한 strtok() 분할 오류
제발 내가 뭘 도와 드릴까요? 오류가 발생하는 위치의
['malloc()'의 반환 값과'C'의 패밀리를 형 변환하지 않는 이유에 대한이 토론을 참조하십시오.] (http://stackoverflow.com/q/605845/2173917). –
'malloc()'이 어떻게 성공했는지 어떻게 알 수 있습니까? –
[___MCVE___] (http://stackoverflow.com/help/mcve)를 만드시겠습니까? –