Saturday, 24 September 2016

memory leaks - C++ - Is my object being deleted twice if I use a map?




I've been working on a Qt project and I encountered a problem with deleting objects that are being hold in a map. I prepared a simple C++ code to show my problem:



   #include 
#include
#include

using namespace std;

class A

{
public:
int *tab;

A()
{
tab = NULL;
}
~A()
{

if (tab != NULL)
{
delete[] tab;
}
}
};

int main()
{
map mapa;


string name = "MyArray";

A *a = new A;
a->tab = new int[3];
a->tab[0] = 1;
a->tab[1] = 2;
a->tab[2] = 3;

mapa[name] = *a;


delete a;


system("PAUSE");
return 0;
}


After closing the program I get:

Debug Assertion Failed!



_BLOCK_TYPE_IS_VALID
etc..



My question is: why is that? The reason is probably that map gets deleted after I quit the program and it holds an A object (a) that is being deleted before I close the program. However, I passed a value, not an address, so what's the problem?



Isn't that value just copied into the map and held in some different address?


Answer



Yes, you're double-deleting.




Maps copy their elements, and your type has no copy constructor. You're actually copying the A yourself with mapa[name] = *a anyway.



The ownership of the member pointer is also very unclear.



Abide by the rule of three. Ideally avoid the manual dynamic allocation altogether; A should have a std::vector instead.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...