2016-01-14 45 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.