1

I have a very basic function bool read_binary( string filename, double*& buf, int &N) which reads data from a binary file. I call it as:

int N;
double* A = NULL;
read_binfile(inputfile, A, N);
delete[] A;

where read_binfile is

bool read_binfile( string fname, double*& buf, int &N ) { 
    ifstream finp(fname.c_str(), ifstream::binary);

    finp.seekg(0, finp.end);
    N = finp.tellg()/8;
    buf = new double[N];
    finp.seekg(0, finp.beg);
    printf("N = %i\n", N); 
    finp.read( reinterpret_cast<char*>(buf), sizeof(buf[0])*N);

    if( finp ) {
        return true;
    } else {
        return false;
    }
}

I find that if I (naively) loop only read_binfile then this causes a memory leak, whereas if I include double* A = NULL and delete[] A in the loop, then this leak does not occur. Is there any way (inside of read_binfile) to check on this type of error or does this necessitate a correct use of read_binfile where a delete[] must follow without being called again?

drjrm3
  • 4,474
  • 10
  • 53
  • 91

1 Answers1

2

You can use a std::vector<double> for buf. That will automate memory management. Then, you won't need to pass N as an argument either. You can get the size of the buffer from the vector.

bool read_binfile(std::string const& fname,
                  std::vector<double>& buf)
{
   std::ifstream finp(fname.c_str(), std::ifstream::binary);

   finp.seekg(0, finp.end);
   size_t N = finp.tellg()/sizeof(buf[0]);
   buf.resize(N);

   finp.seekg(0, finp.beg);
   finp.read(reinterpret_cast<char*>(buf.data()), sizeof(buf[0])*N);

   if( finp ) {
      return true;
   } else {
      return false;
   }
}

And use it as:

std::vector<double> A;
read_binfile(inputfile, A);
size_t N = A.size(); // Only if needed.
R Sahu
  • 204,454
  • 14
  • 159
  • 270