2012-05-01 14 views
0

ファイルを解析しようとしていて、奇妙なセグメンテーション違反が発生しています。これは私が使用していたコードです:私はcurrent_positionを宣言whileループで行を削除した場合、私は、コマンドファイルを扱うときに奇妙なセグメンテーションエラーが発生する

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); 
関連する問題