簡體   English   中英

這段代碼會導致內存泄漏問題嗎?

[英]Will this code cause memory leak issue?

考慮下面的代碼,如果我像這樣使用Die類的實例會發生什么:

Die d;
d.Roll(20);
d.Roll(15);
d.Roll(30);

在為內存再次分配內存之前,我應該還是不應該釋放值占用的內存? new之前delete[ ]

die.h

#ifndef DIE_H
#define DIE_H
#include<iostream>
#include<time.h>
using namespace std;


class Die
{
private:
    int number;
    int* values;
    int count;
    void roll();
public:
    Die(){srand(static_cast<int>(time(NULL)));number=0;values=NULL;count=0;}
    void Roll(int n);
    int getNumber()const{return number;}
    void printLastValue();
    void printValues();
    ~Die(){delete [] values;}

};

#endif

die.cpp

#include"die.h"
#include<iostream>
#include<time.h>
using namespace std;

void Die::roll()
{

    number=1+rand()%6;
}

void Die::printLastValue()
{
    cout<<number<<endl;
}

void Die::Roll(int n)
{
    count=n;
    values=new int[count];
    for(int i=0;i<count;i++)
    {
        roll();
        values[i]=number;
    }

}
void Die::printValues()
{
    for(int i=0;i<count;i++)
    {
        cout<<values[i]<<endl;
    }
}

main.cpp中

#include"die.h"
#include<iostream>
using namespace std;

int main()
{
    Die d;
    d.Roll(25);
    d.printValues();
    d.Roll(40);
    d.printValues();
    d.Roll(100);
    d.printValues();
    d.printLastValue();
}

是的,如果多次調用Roll ,這將導致內存泄漏。 您應檢查值是否為NULL ,如果不是,則調用delete []

編輯:
如下面所述,您不必檢查null,您可以安全地在空指針上調用delete。 它只是我用來工作的公司標准的長期習慣。

您應該研究使用std::vector而不是數組。 通過這樣做,您將消除內存泄漏的危險,您將不再需要顯式定義析構函數。 你可以用這個替換你的values

std::vector<int> values;

然后在您的Roll代碼中,您可以這樣做:

void Die::Roll(int n) {
    count=n;
    values.clear();
    for(int i=0;i<count;i++)
    {
        roll();
        values.push_back(number);
    }
}

你肯定需要刪除它們,因為你重新分配Die ::值,導致內存泄漏。

編輯:在這種情況下,使用std :: vector比使用原始數組更好。 然后你不需要刪除任何東西,只需在Die :: Roll的開頭調用std :: vector :: clear。

是的,它會泄漏內存。 當你這樣做

Values = new int [len];

它為陣列分配新內存並將值指向新內存位置。 舊內存位置仍包含舊數據,需要在分配新數據之前將其刪除。

暫無
暫無

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

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