Я пытаюсь загрузить двоичный файл, но получаю:
realloc(): invalid next size
Это структура, которую я использую в следующем коде:
typedef struct {
int from;
int to;
int cost;
} edge_t;
typedef struct {
int size;
int capacity;
edge_t *edges;
} graph_t;
Код:
#include <stdlib.h>
#include <stdio.h>
#include "graph.h" //this is the struct above
void load_bin(const char *fname, graph_t *graph) {
graph->capacity = 1;
graph->size = 0;
graph->edges = malloc(graph->capacity*sizeof(edge_t));
FILE *myFile;
myFile = fopen(fname, "r");
if (myFile == NULL) {
fprintf(stderr, "Error: file not found!\n");
exit(100);
}
while(fread(&(graph->edges[graph->size].from), sizeof(edge_t), 3, myFile) == 3){
graph->size++;
if(graph->capacity == graph->size){
graph->capacity *=2;
graph->edges=realloc(graph->edges, sizeof(edge_t)*graph->capacity);
}
}
}
РЕДАКТИРОВАТЬ: Попытка сделать проверяемый пример, как требуется.
int main(int argc, char *argv[])
{
int ret = 0;
if (argc > 2) {
graph_t *graph = allocate_graph();
fprintf(stderr, "Load bin file '%s'\n", argv[1]);
load_bin(argv[1], graph);
fprintf(stderr, "Save txt file '%s'\n", argv[2]);
save_txt(graph, argv[2]);
free_graph(&graph);
} else {
fprintf(stderr, "Usage %s input_bin_file output_txt_file\n", argv[0]);
ret = -1;
}
return ret;
}
Эта функция и загрузка расположены в одном файле и вызываются из основного
graph_t *allocate_graph(){
return calloc(1, sizeof(graph_t));
}
Из того, что я проверил, это означает, что я не изменяю размер должным образом в realloc,но я думал, что был?
Спасибо.