2011-11-09 77 views
0

我需要從二進制文件中讀取兩個動態分配的矢量。 最終會出現Segmentation Fault錯誤,但即使fread()完成時沒有問題,矢量仍然充滿零(有時包含零/「垃圾」)。從二進制文件讀取動態分配的矢量

下面是我用它來閱讀它的代碼:

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

這些都是越野車(你正在破壞你的棧):

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測試你的程序。經常這樣做,它會爲你節省很多時間。

+0

Ty,解決了這個問題,我也來看看這個Valgrind。 – Imperian