dimanche 7 octobre 2018

fread segfaults with correct file length and buffer allocation

I have code that saves a 2D float array into a binary file, and another code that reads the binary file and puts it in a 2D float array.

void write2DArrayToBinary(const char* file_name, void** array, size_t len_1D, size_t len_2D, size_t num_bytes_per_elem) {
  FILE* file = fopen(file_name, "wb");
  for (size_t i = 0; i < len_1D; i++) {
    fwrite(array[i], num_bytes_per_elem, len_2D, file);
  }
  fclose(file);
}

void read2DArrayFromBinary(void** array, size_t len_1d, size_t len_2d, size_t num_bytes_per_elem, const char* file_name) {
  FILE* file = fopen(file_name, "rb");
  for (size_t i = 0; i < len_1d; i++) {
    array[i] = malloc(num_bytes_per_elem * len_2d);
    fread(array[i], num_bytes_per_elem, len_2d, file);
  }
  fclose(file);
}

I call the read function like this ( I have omitted irrelevent code ) :

this->dilate_weights_prev = (float**)malloc(sizeof(float*) * this->num_layers);
read2DArrayFromBinary((void**)this->dilate_weights_prev, this->num_layers, this->dilate_weights_prev_len, sizeof(float), fileName);

I have checked that the len_1D and len_2D in write2DArrrayToBinary and read2DArrayFromBinary are the same. Also, I have used gdb, and the read function segfaults on its first iteration.

What do you think cold be causing this?

Aucun commentaire:

Enregistrer un commentaire