Segmentation fault when reading a binary file into a structure

北慕城南 提交于 2019-12-24 12:11:44

问题


I'm experiencing some problems while trying to read a binary file in C. This problem never happened to me before, I don't really know how to manage it.

So, there's this structure called "hash_record", there are many of them stored in my "HASH_FILE" file in binary mode. This is the structure:

typedef struct hash_record {
char *hash;
char *filename;
} hash_record;

I write the file in this way:

hash_record hrec;
[...] code that fill the structure's fields [...]
FILE* hash_file = fopen(HASH_FILE, "ab");
fwrite(&hrec, sizeof(hash_record), 1, hash_file);
fclose(shared_file);

This is just a summary, the fwrite() function is inside a loop so that I can fill the file with many hash_record's. Then, immediately after that piece of code, I start reading the file and printing some data to be sure everything went well. This is the code:

int print_data() {
hash_record rec;

printf("Data:\n");
FILE* hash_file = fopen("hash.bin", "rb");
if (hash_file == NULL)
    return -1;
while(fread(&rec, sizeof(hash_record), 1, hash_file) == 1)
    printf("Filename: %s - Hash: %s", rec.filename, rec.hash);
fclose(hash_file);
return 0;
}

And everything works just fine! The problem is that if I write the binary file in an instance of my program and then quit it, when I open it again (commenting the code which write the file so it can only read it) it gives me a Segmentation Fault. This error appears when I call the printf() inside the while() loop. If I just print a common string without calling "rec" no errors are given, so I'm assuming there's something wrong storing data inside "rec".

Any idea?

Thank you!


回答1:


You are writing out pointers. When you read them back in from the same instance of the program, the data is in the same place and the pointers are meaningful. If you read them in from another instance, the pointers are bad.



来源:https://stackoverflow.com/questions/9854583/segmentation-fault-when-reading-a-binary-file-into-a-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!