Search code examples
cc++11file-ioiofread

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);
}

The former is inside a .C file and the latter is in a .CC ( c++11 ). 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?


Solution

  • To summarize what I already wrote in the comments: You call several POSIX functions (fread, malloc, and fopen, to name a few) without checking their return values. Any of these functions can fail for a number of reasons. If you want your program to be robust, you should not proceed to the next statement without checking if the previous function call was successful. In particular, both fopen and malloc can return a NULL. Make sure they don't.