简体   繁体   中英

Will this code cause memory leak issue?

Considering the code below, what happens if i use an instance of Die class like this:

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

Should I or should I not free the memory occupied by values before alocating again memory for it? delete[ ] before 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

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();
}

Yes, this will cause a memory leak if you call Roll multiple times. You should check if values is NULL and call delete [] if it is not.

EDIT:
As commented below, you do not have to check for null, you can safely call delete on a null pointer. Its just a long engrained habit from company standards where I use to work.

You should look into using a std::vector instead of the array. By doing this you will remove the danger of a memory leak and you will no longer need to explicitly define a destructor. You could replace your the values with this:

std::vector<int> values;

Then in your Roll code you could do this:

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

You definitely need to delete them because you are reassigning Die::values, causing memory leaks.

EDIT: in this case it's better to use std::vector than a raw array. Then you don't need to delete anything, but simply call std::vector::clear at the beginning of Die::Roll.

Yes, it will leak memory. When you do

Values = new int [len];

It allocates new memory with the array and points values to the new memory location. The old memory location still contains the old data which needs to be deleted before the new data can be allocated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM