1
我有一个非常基本的功能bool read_binary(string filename, double*& buf, int &N)
从二进制文件读取数据。我叫它为:有没有办法检查这个内存泄漏?
int N;
double* A = NULL;
read_binfile(inputfile, A, N);
delete[] A;
其中read_binfile
是
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;
}
}
我觉得,如果我(天真)环只有read_binfile
那么这会导致内存泄漏,而如果我有double* A = NULL
和delete[] A
在循环,那么这个泄漏不会发生。是否有任何方法(在read_binfile
之内)检查这种类型的错误,或者是否需要正确使用read_binfile
,其中delete[]
必须遵循而不被再次调用?
使用'的std :: VECTOR',然后你不必担心。 – NathanOliver
'vector'不能保证内存是连续的,我需要在算法中利用局部性。 – drjrm3
是的。 http://stackoverflow.com/a/849190/2101267 –