Magno Silva Magno Silva - 9 months ago 33
C++ Question

Problems with memory leak in C++

In a constructor I'm initializing a pointer like this:

Rectangle::Rectangle(GLfloat screenWidth, GLfloat screenHeight, glm::vec3 color) : screenWidth(screenWidth), screenHeight(screenHeight), color(color) {

renderer = new Engine::SpriteRenderer(Engine::ResourceManager::getShader("Primitive_shader"), 1);

}


I'm instantiating Rectangle objects and thus calling the constructor in a function called "draw", and "draw" is in a while loop, here is sample of draw:

void Game::draw( ) {

Engine::Primitives::Rectangle rect(widthScreen, heightScreen, glm::vec3(1.0f, 1.0f, 0.0f));

Engine::Primitives::Rectangle rectHead(widthScreen, heightScreen, glm::vec3(1.0f, 1.0f, 0.0f));
Engine::Primitives::Rectangle rectBody(widthScreen, heightScreen, glm::vec3(1.0f, 1.0f, 0.0f));

Engine::Primitives::Rectangle rectHeadPlayer(widthScreen, heightScreen, glm::vec3(1.0f, 1.0f, 0.0f));
Engine::Primitives::Rectangle rectBodyPlayer(widthScreen, heightScreen, glm::vec3(1.0f, 1.0f, 0.0f));

}


in order to realese the memory allocated for renderer in the constructor I'm calling delete in the destructor like this:

Rectangle::~Rectangle( ) {

delete renderer;

}


But, for some reason, the memory allocated for renderer is still not being released. When I look the windows task manager the ram memory consumed by my program keeps increasing more and more. I know for a fact that the Rectangle constructor is the cause for this memory leak because when I comment the lines for the objects instantiation in draw the memory consumed by my program gets stable as it should. Can somebody tell me what might be going on?

Answer Source

Calling delete does not necessarily hand the memory back to the operating system - in fact, it mostly won't do that, it will hand it back to the C++ runtime library.