Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using delete with a base class pointer cause a memory leak?

Tags:

Given two classes have only primitive data type and no custom destructor/deallocator. Does C++ spec guarantee it will deallocate with correct size?

struct A { int foo; };
struct B: public A { int bar[100000]; };
A *a = (A*)new B;
delete a;

I want to know do I need to write an empty virtual dtor?

I have tried g++ and vc++2008 and they won't cause a leak. But I would like to know what is correct in C++ standard.

like image 209
kcwu Avatar asked Jan 20 '10 10:01

kcwu


People also ask

What will happen when a base class pointer is used to delete the derived?

Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, following program results in undefined behavior.

Which destructor can be used to avoid a memory leak?

However, once an inheritance hierarchy is created, with memory allocations occurring at each stage in the hierarchy, it is necessary to be very careful about how objects are destroyed so that any memory leaks are avoided. In order to achieve this, we make use of a virtual destructor.

How smart pointer avoids the problem of memory leak?

Smart pointers allow you to forget about manual allocation and can help avoid most memory leaks. On managed platforms, an object gets destroyed when there are no references to it. The garbage collection builds a graph of references to free objects even if they have references to each other.

How are memory leaks caused in C++?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.


1 Answers

Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4:

If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is undefined.

like image 83
James Hopkin Avatar answered Oct 22 '22 15:10

James Hopkin