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?