2012-05-01 3 views
0

파일을 구문 분석하려고하는데 이상한 세그먼테이션 오류가 발생합니다. 이것은 내가 사용하고있는 코드입니다 : 내가 CURRENT_POSITION를 선언하면서 루프 라인을 제거하면 내가 명령파일 처리시 이상한 세그먼테이션 오류가 발생했습니다.

g++ -Wall -o parse_file parse_file.cpp 

로 컴파일

#include <iostream> 

using namespace std; 

int main() 
{ 
    FILE *the_file; 
    the_file = fopen("the_file.txt","r"); 

    if (the_file == NULL) 
    { 
     cout << "Error opening file.\n"; 
     return 1; 
    } 

    int position = 0; 
    while (!feof(the_file)) 
    { 
     unsigned char *byte1; 
     unsigned char *byte2; 
     unsigned char *byte3; 
     int current_position = position; 

     fread(byte1, 1, 1, the_file); 
    } 
} 

코드는 문제없이 실행됩니다. 나는 또한 그 선언을 부호없는 char 포인터의 선언들 위로 옮길 수 있고 코드는 문제없이 실행될 것이다. 왜 그 선언문에 왜 잘못 됐어?

답변

8

byte1은 초기화되지 않은 포인터입니다. 일부 저장 영역을 할당해야합니다.

unsigned char *byte1 = malloc(sizeof(*byte1)); 

fread(&byte1, 1, 1, the_file); 

... 

free(byte1); 

또는 더 나은

, 모든 포인터 사용하지 마십시오

unsigned char byte1; 

fread(&byte1, 1, 1, the_file); 
관련 문제