I’m trying to create a simple game, but I can’t find a certain memory leak. Every second or so, the program seems to use 3mb more memory.
The problem is with this draw method. If I don’t call this method, everything works fine. I’m trying to paint a sprite on several parts of the screen:
void Map::draw(HDC hBackBufferDC)
{
for(int i = 0; i < 24; i++)
{
for(int j = 0; j < 27; j++)
{
if(mapState[i][j] == 'm')
{
blueWall->draw(hBackBufferDC, new Position(j, i));
}
}
}
}
If I remove the method call of draw, there are no problems, so the problem is in that method:
void StaticSprite::draw(HDC hBackBufferDC, Position* pos)
{
int x = (int)pos->x * 22;
int y = (int)pos->y * 22;
HGDIOBJ oldObj = SelectObject(this->hSpriteDC, this->hMask);
BitBlt(hBackBufferDC, x, y, 22, 22, this->hSpriteDC, 0, 0, SRCAND);
SelectObject(this->hSpriteDC, this->hImage);
BitBlt(hBackBufferDC, x, y, 22, 22, this->hSpriteDC, 0, 0, SRCPAINT);
SelectObject(this->hSpriteDC, oldObj);
}
Any idea what is causing the memory leak here? I think it’s related to this part, but I can post other parts of the code if needed.
Thanks
Are you using managed c++ or not ?
You are allocating new Position (24*27) times.
This lead to a 648 leaks each time you call Map::draw.
Use an automatic object.
Or delete the Position object after using it !
Note that dynamic allocation is very slow.