2012-05-01 77 views
0

我想解析一个文件,并且出现奇怪的分段错误。这是我使用的代码:处理文件时出现奇怪的分割错误

#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); 
    } 
} 

我用命令

g++ -Wall -o parse_file parse_file.cpp 

编译它,如果我删除行while循环声明CURRENT_POSITION,代码运行没有问题。我也可以将这个声明移到unsigned 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);