Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory leak when deleting derived class with base-class pointer

I have an issue with a memory leak. I have a base-class pointer. From it, I use new to allocate different derived classes. Then, when I try to delete those classes with the reference (not typecasted), I get a memory leak. I researched the problem and found that I should add a virtual destructor to the base-class, but I tried this and I still have a memory leak; that is, according to my task-manager, the memory usage continues to rise with each allocation and deletion of the derived class using the base-class pointer. I tried making it an abstract destructor and added destructors to the derived classes, but I got an undefined reference error. I also tried typecasting the pointer as a derived-class pointer for the delete, but apparently this crashes the program.

Does anyone have any idea what I should do?

Example code:

class A {
public:
  A();
  ~A() {};
  virtual ~A();      /*or*/
  virtual ~A()=0;    /*or*/
                     /*or nothing?*/
}

class B: private A {
public:
  B();
  ~B() {};           /*this?*/
                     /*or nothing?*/
}
like image 590
Codesmith Avatar asked Mar 03 '11 21:03

Codesmith


1 Answers

How sure are you that there really is a memory leak? Normally, the task manager won't be much help here, since it cannot tell how much of the memory belonging to your process is actually allocated. Even memory that is freed still belongs to your process, and may be used at later times by the memory management (normally malloc-like system library).

Use a tool such as mallocdebug, valgrind, purify etc. to find out if there's really a memory leak. These tools will replace the malloc implementation by a new one that keeps track of allocated memory and reports memory that is not freed upon process termination.

Note: On most systems, memory that is freed from a process is not returned to the system before the process exits. It is availabe for new allocations from within the same process, though.

like image 174
Axel Avatar answered Oct 19 '22 23:10

Axel