954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Memory leak (vector, methinks)

I'm having several difficulties with memory leaks in a program (I've been using "Visual Leak Detector" to check for memory leaks). I've simplified the code to the following:

#include "vld.h"
#include "vldapi.h"
#include <string>
#include <vector>

class BaseFoo {
public:
	BaseFoo() {}
	~BaseFoo() {}
};

class ButtonFoo {
public:
	void setText( std::string text ) { _text = text; }

private:
	std::string _text;
};

class InheritedFoo : public BaseFoo {
public:
	InheritedFoo();

private:
	ButtonFoo buttons[4];
};

InheritedFoo::InheritedFoo()
{	
	ButtonFoo button;

	for( unsigned int i = 0; i < 4; i++ ) { 
		buttons[i] = button;
	}

	buttons[0].setText( "NO MORE MEMORY LEAKS" );
	buttons[1].setText( "I DONT LIKE YOU ANYMORE" );
	buttons[2].setText( "I DONT WANT YOU ANYMORE" );
	buttons[3].setText( "GO AWAY" );
}

int main( int argc, char **argv )
{
	std::vector<BaseFoo*> modules;

	modules.push_back( new InheritedFoo() );
	
	for( unsigned int i = 0; i < modules.size(); ++i ) {
		delete modules[i];
	}
}


I suspect 'modules' is the source of the memory leak. Why is the vector leaking memory? And is there a way around it?

Evan M
Light Poster
42 posts since Sep 2007
Reputation Points: 11
Solved Threads: 5
 

Your loop, where you have buttons[i] = button... yeah, that doesn't create new instances of ButtonFoo. You are taking button[0] and pointing it to button. Then taking button[1] and pointing it to the same object as button[0]....

Comatose
Taboo Programmer
Team Colleague
2,910 posts since Dec 2004
Reputation Points: 361
Solved Threads: 215
 
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
 

A classical case. Only base class destructor called because your BaseFoo is not a polymorphic class. It can't deallocate any vectors in the derived class: it knows nothing about its descendants.
Make it as a polymorphic class (fortunately, it's so simple) and see what happens:

class BaseFoo {
public:	
  BaseFoo() {}
  virtual ~BaseFoo() {}
};
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

Thanks for the help. I always assumed since the constructor isn't virtual, the destructor wouldn't have to be either. The memory leaks are gone :)

Evan M
Light Poster
42 posts since Sep 2007
Reputation Points: 11
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You