I use dynamic memory allocation in my code, and I'm having trouble trying to remove a pointer to a subclass. I found that the initially allocated memory is not freed when I use the delete keyword. Functionality works great with the original base class.
This is a problem because I run the code on arduino, and RAM quickly eats up and then crashes.
Here is a sample code:
class Base { public: Base(){ objPtr = new SomeObject; } ~Base(){ delete objPtr; } SomeObject* objPtr; }; class Sub : public Base { public: Sub(){ objPtr = new SomeObject; } }; // this works fine int main() { for (int n=0;n<100;n++) // or any arbitrary number { Base* basePtr = new Base; delete basePtr; } return 0; } // this crashes the arduino (runs out of RAM) int main() { for (int n=0;n<100;n++) // or any arbitrary number { Sub* subPtr = new Sub; delete subPtr; } return 0; }
I assume this has something to do with the destructor syntax in the base class. Even if I create a custom destructor for a subclass, the same problems occur.
Any ideas?
source share