views:

247

answers:

2

I've been trying to swap images in a PictureBox in a C++/CLI application but my solution appears to have a memory leak:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
 // Pick a new bitmap
 static int resource = IDB_BITMAP1;
 if( resource == IDB_BITMAP2)
 {
  resource = IDB_BITMAP1;
 }
 else
 {
  resource = IDB_BITMAP2;
 }

 // Get the primary module
 Module^ mod = Assembly::GetExecutingAssembly()->GetModules()[0];

 // Get the instance handle 
 IntPtr hinst = Marshal::GetHINSTANCE(mod);

 // Get the bitmap as unmanaged
 HANDLE hbi = LoadImage((HINSTANCE) hinst.ToPointer(),MAKEINTRESOURCE(resource),IMAGE_BITMAP,0,0,LR_DEFAULTCOLOR); 

 // Import the unmanaged bitmap into the managed side 
 Bitmap^ bi = Bitmap::FromHbitmap(IntPtr(hbi));

 // Remove any previously stored images
 if(m_pictureBox1->Image != nullptr)
 {
  delete m_pictureBox1->Image;
  m_pictureBox1->Image = nullptr;
 }

 // Insert the bitmap into the picture box
 m_pictureBox1->Image = bi;

 // Free up the unmanaged bitmap
 DeleteObject(hbi);
}

As far as I can see, I'm explicitely releasing the memory so why does task manager report an ~24k increase in memory each time the button is clicked?

+1  A: 

two words: garbage collection

KristoferA - Huagati.com
That was my initial reaction, but explicitely deleted the objects should get around those effects shouldn't they?
Jon Cage
I think the cleanup will only clean up the unmanaged side. The rest will be cleaned up by GC at a later point in time...
KristoferA - Huagati.com
That would make sense..
Jon Cage
A: 

Bizarrely, this actually looks to be caused when you mouse-over the button. Each time you do that the memory jumps but after enough mouse-overs that memory usage stabilises. The actual clicks on the button (i.e. calls to my routine) don't cause any leakage.

Jon Cage