Friday 27 October 2017

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 A> 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?


class="post-text" itemprop="text">
class="normal">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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...