Загрузка двоичного файла - realloc (): неверный следующий размер - PullRequest
0 голосов
/ 23 декабря 2018

Я пытаюсь загрузить двоичный файл, но получаю:

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,но я думал, что был?

Спасибо.

1 Ответ

0 голосов
/ 23 декабря 2018

значение while недопустимо, должно быть

while(fread(&(graph->edges[graph->size].from), sizeof(edge_t), 1, myFile) == 1)

, потому что в настоящее время вы читаете 3 элемента и выходите из выделенной памяти

PS из этого вы уверены, что правильно прочиталифайл ?вы полагаете, что содержимое состоит из 3 последовательных значений по sizeof(int) байтов, без разделителя и т. д.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...