2016-01-14 49 views
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 = NULLdelete[] A在循环,那么这个泄漏不会发生。是否有任何方法(在read_binfile之内)检查这种类型的错误,或者是否需要正确使用read_binfile,其中delete[]必须遵循而不被再次调用?

+5

使用'的std :: VECTOR',然后你不必担心。 – NathanOliver

+0

'vector'不能保证内存是连续的,我需要在算法中利用局部性。 – drjrm3

+7

是的。 http://stackoverflow.com/a/849190/2101267 –

回答

2

您可以使用std::vector<double>作为buf。这将自动执行内存管理。然后,您也不需要通过N作为参数。您可以从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; 
    } 
} 

而且使用它作为:

std::vector<double> A; 
read_binfile(inputfile, A); 
size_t N = A.size(); // Only if needed.