| | |
Memory leak (vector, methinks)
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
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:
I suspect 'modules' is the source of the memory leak. Why is the vector leaking memory? And is there a way around it?
C++ Syntax (Toggle Plain Text)
#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?
•
•
Join Date: Nov 2007
Posts: 978
Reputation:
Solved Threads: 208
Read about When should my destructor be virtual?
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:
Make it as a polymorphic class (fortunately, it's so simple) and see what happens:
c++ Syntax (Toggle Plain Text)
class BaseFoo { public: BaseFoo() {} virtual ~BaseFoo() {} };
Last edited by ArkM; Mar 10th, 2009 at 8:16 pm.
![]() |
Other Threads in the C++ Forum
- Previous Thread: C++ and Polymorphism
- Next Thread: variable trouble?
| Thread Tools | Search this Thread |
api array arrays based beginner binary bitmap c++ c/c++ calculator char class classes code compile compiler console conversion count delete deploy desktop directshow dll download dynamic dynamiccharacterarray encryption error file forms fstream function functions game getline givemetehcodez google graph gui homeworkhelp homeworkhelper iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory news node output parameter pointer problem program programming project proxy python read recursion recursive reference return rpg string strings struct temperature template templates test text text-file tree unix url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






