tags:

views:

47

answers:

2

Hello world.

I had a bug in my program, so I did some experiments and found the following code ends up

throws an exception after running for a while.

while ( 1 )
{
    System::Drawing::Bitmap^ pBitmap = gcnew System::Drawing::Bitmap( 500, 500 );
    this->Cursor = gcnew System::Windows::Forms::Cursor(pBitmap->GetHicon());
}

I can't find any clue to that exception.

What's wrong?

So I change the code to this

while ( 1 )
{
    System::Drawing::Bitmap^ pBitmap = gcnew System::Drawing::Bitmap(500,500);                                
    System::Windows::Forms::Cursor^ pCursor = gcnew System::Windows::Forms::Cursor(pBitmap->GetHicon());                                                               

    delete pBitmap;
    delete pCursor;                
}

The same exception still gets thrown.

Any clue will be thankful.

+2  A: 

When you create bitmaps you request memory (500 * 500 * bytesPerPixeL) and internal GDI handles. The number of available handles is quite big, but limited. So, my guess would be that you either run out of memory before the garbage collector kicks in or you run out of GDI handles.

You should use using (pBitmap = ... ) in order to call Dispose() automatically or call Dispose() manually when you're done. Same goes for the Cursor.

The MSDN article GDI Objects says:

"There is a theoretical limit of 65,536 GDI handles per session. However, the maximum number of GDI handles that can be opened per session is usually lower, since it is affected by available memory."

But both of Bitmap and Cursor don't have dispose method
shawn
@shawn: `IDisposable` on those classes is implemented using an explicit interface implementation. You will have to cast to that interface to use it.
Martin Liversage
A: 

I recreated the problem, and it looks like this: Screenshot

When I looked at the task manager, my memory consumption while running the program for the first 5000 run-throughs looked like I expected. The graph was growing while allocating memory for new images, and decreasing while the GC released the memory - However, releasing the memory never seemed to be perfect, as the value it dropped to during decreases kept rising. This leads me to believe that you have some sort of memoryleak.

-- and so, my Sherlock Holmes skills came to a hault, and my Columbo skills took over. What could be causing such a leak? Hmm.. forgetting to call .Dispose()? Yup, Bitmap indeed does implement IDisposable, sooo, you should remember to call .Dispose() on your bitmap before you create a new one :)

cwap