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 –