I am trying to load a binary file but I am getting:
realloc(): invalid next size
This is the struct im using in the following code:
typedef struct {
int from;
int to;
int cost;
} edge_t;
typedef struct {
int size;
int capacity;
edge_t *edges;
} graph_t;
Code:
#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);
}
}
}
EDIT: Tried to make a verifiable example, as requested.
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;
}
This function and load are located in the same file and are called from main
graph_t *allocate_graph(){
return calloc(1, sizeof(graph_t));
}
From what I checked, it means I do not change the size properly on realloc, but I thought i was?
Thanks.