Quick question; I’ve googled around and found some answers already, but I’m a bit paranoid so I want to be sure.
Consider this situation:
struct CoordLocation
{
float X;
float Y;
float Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Will calling delete also clear the memory used by the fields X, Y, Z? Some answers I found mentioned that I’d just delete the POINTER, not the actually referenced object this way.
What if…
struct CoordLocation
{
float *X;
float *Y;
float *Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
And what if I manually free the memory for each object inside the struct’s constructor/destructor?
struct CoordLocation
{
CoordLocation()
{
*X = new float;
*Y = new float;
*Z = new float;
}
~CoordLocation()
{
delete X; delete Y; delete Z;
}
float *X;
float *Y;
float *Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
I noticed that for a simple situation such as:
float *a = new float;
*a = 5.0f;
printf("%f", *a);
delete a;
printf("%f", &a);
printf would print 5.0, so the variable pointed to by a is not exactly destroyed.
So my question is:
How can I reliably free (as in no memory leaks) ALL the memory used by the struct in this case?
struct CoordLocation
{
float X;
float Y;
float Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Thanks!
You only need to
deletememory you allocate withnew.You’re actually running into undefined behavior. Although the value is still there, the memory was released and can be reused.
So the following:
can’t create a memory leak if you omit the destructor.
Your next snippet:
can potentially create a memory leak, but not as it is. The following will:
Your third example
won’t create a memory leak because you free all the memory that you allocate. If you were to omit the destructor or forget to call
delete coord;, they you’d have a memory leak.A good rule of thumb: call a
deletefor everynewand adelete[]for everynew[]and you’re safe.