[英]Is there a way to check for this memory leak?
I have a very basic function bool read_binary( string filename, double*& buf, int &N)
which reads data from a binary file. 我有一个非常基本的函数
bool read_binary( string filename, double*& buf, int &N)
,它从二进制文件中读取数据。 I call it as: 我称其为:
int N;
double* A = NULL;
read_binfile(inputfile, A, N);
delete[] A;
where read_binfile
is 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;
}
}
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. 我发现如果我(天真的) 仅循环
read_binfile
那么这会导致内存泄漏,而如果我在循环中包含double* A = NULL
并delete[] A
,则不会发生此泄漏。 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? 是否有任何方法(在
read_binfile
)检查这种类型的错误,或者这是否需要正确使用read_binfile
,在该情况下必须遵循delete[]
而不再次调用它?
You can use a std::vector<double>
for buf
. 您可以将
std::vector<double>
用于buf
。 That will automate memory management. 这将自动执行内存管理。 Then, you won't need to pass
N
as an argument either. 然后,您也不需要将
N
作为参数传递。 You can get the size of the buffer from the vector
. 您可以从
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.