2016-09-09 5 views
-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() 분할 오류

제발 내가 뭘 도와 드릴까요? 오류가 발생하는 위치의

+0

['malloc()'의 반환 값과'C'의 패밀리를 형 변환하지 않는 이유에 대한이 토론을 참조하십시오.] (http://stackoverflow.com/q/605845/2173917). –

+0

'malloc()'이 어떻게 성공했는지 어떻게 알 수 있습니까? –

+3

[___MCVE___] (http://stackoverflow.com/help/mcve)를 만드시겠습니까? –

답변

1

귀하의 분석은

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

사실, 제어가 도달 않습니다 올바르지 않습니다. 개행이나 플러시가 없으므로 "AFTER"메시지가 표시되지 않습니다. 이에 코드를 변경하고 신비가 사라집니다 :

printf("AFTER\n"); 

나는 그것이 출력을 플러시 main의 끝을 도달 않기 때문에 당신이 당신의 MCVE와 오류를 복제 할 수 겠지. MCVE에서 "V"를 잊어 버렸습니다. 문제가 복제되는지 확인해야합니다.