这段代码会导致内存泄漏问题吗?

lau*_*ura 2 c++ visual-c++

考虑下面的代码,如果我使用这样的Die类实例会发生什么:

Die d;
d.Roll(20);
d.Roll(15);
d.Roll(30);
Run Code Online (Sandbox Code Playgroud)

在为内存再次分配内存之前,我应该还是不应该释放值占用的内存?delete[ ]之前new

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
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

pst*_*jds 5

是的,如果Roll多次调用,这将导致内存泄漏.您应检查值是否为NULL,delete []如果不是则调用.

编辑:
如下面评论,您不必检查null,您可以安全地调用空指针上的删除.它只是我用来工作的公司标准的长期习惯.

你应该考虑使用a std::vector而不是数组.通过这样做,您将消除内存泄漏的危险,您将不再需要显式定义析构函数.你可以values用这个替换你的:

std::vector<int> values;
Run Code Online (Sandbox Code Playgroud)

然后在您的Roll代码中,您可以这样做:

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

  • 每次只调用`delete []`,因为delete []对空指针不做任何操作. (3认同)