Problems freeing memory in a copy constructor
I have this parent class
class Monster
{
char* nume;
double hp;
float* dmgAbilitati;
int nrAbilitati;
}
with this copy constructor
Monster(const Monster& src)
{
if (nume != nullptr)
delete[] nume;
this->nume = new char[strlen(src.nume) + 1];
strcpy_s(this->nume, strlen(src.nume) + 1, src.nume);
this->hp = src.hp;
this->nrAbilitati = src.nrAbilitati;
if (dmgAbilitati != nullptr)
delete[] dmgAbilitati;
this->dmgAbilitati = new float[this->nrAbilitati];
for (int i = 0; i < this->nrAbilitati; i++)
this->dmgAbilitati[i] = src.dmgAbilitati[i];
}
and I am asking if it is mandatory to use these statements
if (nume != nullptr)
delete[] nume;
if (dmgAbilitati != nullptr)
delete[] dmgAbilitati;
because I am trying to overload the pre/post-increment operator in this child class
class giantSpider : private Monster
{
int durataStun;
.
.
.
const giantSpider operator++(int)
{
giantSpider aux(*this);
durataStun++;
return aux;
}
}
and it throws an exception like in the image below(sometimes works tho), and if I'm not including those statements, everything is fine.
I am using this constructor to initialize the parameters
Monster(const char* nume, double hp, int nrAbilitati, float* dmgAbilitati)
{
if (nume == nullptr)
throw new exception("Nume invalid!\n");
else
{
this->nume = new char[strlen(nume) + 1];
strcpy_s(this->nume, strlen(nume) + 1, nume);
}
if (hp <= 0)
throw new exception("Hp invalid!\n");
else
this->hp = hp;
if (nrAbilitati <= 0 && dmgAbilitati == nullptr)
throw new exception("nrAbilitati invalid sau dmgAbilitati invalid!\n");
else
{
this->nrAbilitati = nrAbilitati;
this->dmgAbilitati = new float[nrAbilitati];
for (int i = 0; i < nrAbilitati; i++)
this->dmgAbilitati[i] = dmgAbilitati[i];
}
}
and for the child:
giantSpider(const char* nume, double hp, int nrAbilitati, float* dmgAbilitati, int durataStun)
:Monster(nume, hp, nrAbilitati, dmgAbilitati)
{
if (durataStun <= 0)
throw new exception("Numar introdus invalid!\n");
else
this->durataStun = durataStun;
}
and this is in main:
float v1[] = { 125,234.22,8643.3 };
giantSpider g2("Ana", 1000, 3, v1, 3);
cout << g2 << ++g2 << g2++ ;
I have already overloaded the << operator.
https://i.stack.imgur.com/u6kiz.png
Solution 1:
These statements
if (nume != nullptr)
delete[] nume;
if (dmgAbilitati != nullptr)
delete[] dmgAbilitati;
do not make a sense because the data members nume
and dmgAbilitati
are not initialized yet. More precisely neither memory was allocated where they would point to.
So these statements invoke undefined behavior.