2017-04-04 58 views
0

我正在上一個C++的類,我需要編寫一個簡單的程序,故意泄漏內存。我試圖通過創建new char []而不是刪除它們,但這似乎不起作用。以下是我嘗試過的完整代碼。在c + +中的內存泄漏

#include <iostream> 
#include <cstring> 

int main() 
{ 
    int i=1; 
    while (i<1000){ 
     char *data = new char [100000000]; 
     *data = 15; 

     i++; 
    } 
} 

當我觀察程序的內存使用情況時,它不會增長,因此它不會泄漏任何內存。我只是得到一個錯誤的分配錯誤。

+3

請定義*「似乎不起作用」* – WhiZTiM

+0

檢查您的進程內存。它會隨着循環而增加 –

+0

當我觀察程序的內存使用情況時,它不會增長,因此它不會泄漏任何內存。我只是得到一個錯誤的分配錯誤。 –

回答

2

我認爲最簡單的內存泄漏情況是動態創建一個對象,然後立即失去對它的引用。在這個簡短的例子中,您立即失去了對您創建的變量的引用,導致內存泄漏。內存泄漏在像這些小型的,人爲設計的程序中使得難以理解內存泄漏,因爲一旦程序退出,操作系統就會回收程序分配的內存。

當程序長時間運行時,問題變得嚴重。內存泄露加劇,計算機性能明顯受到阻礙。

例子:

#include <iostream> 

// Object is being created, allocated on the heap then function immediately exits, losing any reference to the object. This is a memory leak 
void createObject() 
{ 
    int* x = new int; 
} 

int prompt() 
{ 
    int response;  
    std::cout << "Run again?\n"; 
    std::cin >> response; 

    return response; 
} 
int main() 
{ 
    while(continue) 
    { 
     createObject(); 

     // Running the program again and again will exacerbate the memory leak. 
     continue = prompt(); 
    } 

    return 0; 
} 

正確的方式在這個人爲的和無用的例子保留對象的引用:

int* createObject() 
{ 
    int* x = new int; 

    return x; 
} 

int main() 
{ 
    // Pointer to the object created in the function in this scope is created, so we still have access to the variable. 
    int* a = createObject(); 

    return 0; 
} 

希望這會有所幫助,祝你好運在你的類!

0

如果你在循環中放了一些延遲,你將能夠看到內存的增長。 您可以使用睡眠或等待來自用戶的輸入。

就像現在一樣,內存膨脹得非常快,直到你用完分配內存。

這不是內存泄漏的經典測試。 在程序結束時測試內存泄漏,看看你是否釋放了所有的內存。