【发布时间】:2017-08-02 04:44:32
【问题描述】:
我在调用 fread() 时遇到分段错误,但我无法确定错误可能出在哪里:
`void charger(Repertoire* parent){
int i;
if (parent == 0){parent = &source;}
FILE* rep_file = fopen("repertoires.bin", "rb");
fread(parent, sizeof(Repertoire), 1, rep_file); //<-------------- here
fclose(rep_file);
//more code...`
作为参考,我的函数charger()在这里被调用:
`int main(int argc, char* argv[]){
int i, j, path = 0;
source.nom = "/.";
disque = (char*) calloc(32000, sizeof(char));
charger(0);
//more code...`
并且Repertoire在这里定义在一个头文件中(builder在.c文件中初始化):
`typedef struct repertoire{
int taille;
int itaille;
char* nom;
struct repertoire* enfants;
int countup;
int icountup;
struct inode* fichiers;
} Repertoire;
Repertoire source;
//more code...`
有人可以帮忙吗?
【问题讨论】:
-
你只产生了几个sn-ps的代码,但是在读取文件时发生错误,当你没有检查文件是否真的被打开时。始终测试来自
fopen的返回值:这是基本的必要条件。请发布显示问题的Minimal, Complete, and Verifiable example。 -
啊,看来我当时对 fopen 的使用不当。我想我可以使用带有 read 选项的 fopen 创建一个文件。这解决了我的问题,谢谢!
标签: c struct segmentation-fault fread