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?

Your loop, where you have buttons = 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]....

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() {}
};

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 :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.