0

I have been trying to use screenshots stored in a HBITMAP and outputting this stored as a PNG image.

However, the code appears to have a memory leak in it, as memory does not appear to be freed up correctly.

void saveAsPNG(HBITMAP h)
{
CImage image;

if(_access(location, 0) == 0)
{
    unlink(location); //Delete the image if currently exists
}


image.Attach(h);

image.Save(location,Gdiplus::ImageFormatPNG);


h = image.Detach();


image.Destroy();
image.ReleaseGDIPlus();
}

This code works, but clearing up memory does not seem to happen. According to the private memory set column in Task Manager, image.Destroy does not affect the memory at all, whilst image.ReleaseGDIPlus appears to clean up some data. The HBITMAP comes from a previous function and is GlobalFreed at a later point in the code seperate to this function.

Is there a line missing?

Alex
  • 1
  • 3
  • ***According to the private memory set column in Task Manager*** That is not the best way to check for memory usage. Freeing memory in `c++` doesn't mean that memory was released from the heap back to the OS. – drescherjm Dec 07 '16 at 14:12
  • Is there a simple tool I can use to check the basic memory usage of the program? – Alex Dec 07 '16 at 14:15
  • @Alex many - you'll find a number of questions on stack overflow asking exactly that. – UKMonkey Dec 07 '16 at 14:18
  • 2
    *"`image.Destroy` does not affect the memory at all"* Of course not. `image` doesn't manage any memory at this point, so `Destroy` is a no-op. Recall that you `Detach`ed it earlier. *"`HBITMAP` ... is `GlobalFree`d at a later point"* That's not the correct way to dispose of an `HBITMAP` object. – Igor Tandetnik Dec 07 '16 at 15:06
  • Saying `h = image.Detach();` is wrong, or at least misleading, because the return value is thrown away when the function exits. – Harry Johnston Dec 07 '16 at 21:38

0 Answers0