簡體   English   中英

C ++中的內存泄漏

[英]Memory leakage in c++

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

#include <iostream> 
#include <cstring>

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

        i++;
    }
}

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

我認為內存泄漏的最簡單情況是動態創建一個對象,然后立即丟失對該對象的引用。 在這個簡短的示例中,您將立即丟失對所創建變量的引用,從而導致內存泄漏。 此類小型人為設計的程序中的內存泄漏使人們很難理解內存泄漏,因為一旦程序退出,操作系統便會回收程序分配的內存。

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

例:

#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;
}

希望這對您有幫助,祝您上課好運!

如果在循環中添加一些延遲,您將能夠看到內存增長。 您可以使用sleep或等待用戶輸入。

現在,內存膨脹如此之快,直到您用完分配內存為止。

這不是內存泄漏的經典測試。 它在程序結尾測試了內存泄漏,以查看是否釋放了所有內存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM