从二进制文件读取动态分配的向量

时间:2011-11-09 16:06:37

标签: file file-io memory-management segmentation-fault

我需要帮助从二进制文件中读取两个dinamic分配的向量。 最终会出现Segmentation Fault错误,但即使fread()没有问题,向量仍会保持零(有时是w / 0和“垃圾”)。

以下是我用来阅读它的代码:

struct Node *node;  
node = (Node *) calloc(GRAPHSIZE,sizeof(Node));

int edgesSize = 2*GRAPHSIZE;

int *edges;
edges = (int *) calloc(edgesSize,sizeof(int));  

FILE * file;

printf("\nLoading graph file...\n");

file = fopen ("graph1M.g","rb");    
fread (&edges, edgesSize * sizeof(int),1,file);
fread (&node, GRAPHSIZE * sizeof(Node),1,file);
fclose(file);

这就是他们被拯救的方式:

int edgesSize = 2*GRAPHSIZE;

struct Node *node;  
node = (Node *) calloc(GRAPHSIZE,sizeof(Node));


int *Edges;
Edges = (int *) calloc(edgesSize,sizeof(int));  


/* put data into the vectors... */


FILE *file;

//writes file:
file = fopen ("graph1M.g","wb");
fwrite (&Edges, edgesSize * sizeof(int),1,file);
fwrite (&node, GRAPHSIZE * sizeof(struct Node),1,file);
fclose(file);

1 个答案:

答案 0 :(得分:1)

这些是错误的(你正在破坏你的堆栈):

fread (&edges, edgesSize * sizeof(int),1,file);
fread (&node, GRAPHSIZE * sizeof(Node),1,file);

你想要这个:

fread (edges, edgesSize * sizeof(int),1,file);
fread (node, GRAPHSIZE * sizeof(Node),1,file);

同样问题fwrite

顺便说一下,如果你在Linux上,你应该用Valgrind测试你的程序。经常这样做,它会为你节省很多时间。