29 December 2012

Memory Leak with Form.Picture Object

When you assign an image to the Picture property of a Form Ocx, and don't release the Picture explicitly, a memory leak occurs when the Form is destroyed.

An image can be assigned using the Form-Editor Properties window in the sidebar. For a Form object the Properties window shows a Picture property that can be assigned an image (bitmap, icon, cursor, GIF, JPEG, and metafiles) by double clicking in the value column. Behind the scenes the LoadForm command - that is used to load a Form created with the Form-Editor - will create a COM Picture object on behalf of the Form. The dynamically allocated Picture COM object is then assigned to the Form.Picture property. 
However, a program may also set a Picture object to the Form.Picture property explicitly in code.

The memory leak occurs when the Form is closed. In the process of destroying all resources the Picture object is simply forgotten. The memory for the image is never released and the reference count on the COM object never reaches zero. Not only the memory necessary to store the image, but the memory allocated for the COM object will remain occupied. The memory used to store a bitmap can be of a considerable size and after some time you may even run out of memory. This most likely will present itself after RUNning a program multiple times within the IDE.

The best place to set the Picture Object to Nothing is within the Form_Destroy() event sub. A program cannot release the object when the Form has gone (==Nothing).

The leaked memory can never be reclaimed, because after the Form is destroyed the pointer to the Picture's COM Object is zeroed out. Selecting 'Cleanup Resources' from the Project menu will not work.

No comments:

Post a Comment