开发者

WIndows function DestroyObject for HBITMP doesn't work very well (memory leak)

I need to create HBITMAP images ve开发者_如何学运维ry often in a C++ program, and of course I need to delete these bitmap after use. The code is similar to this

HBITMAP hBmp;
while(true) {
  hBmp = CreateBitmap(width, height, 1, 8, imageData);
  process(hBmp);
  DeleteObject(hBmp);
}

I have an infinite cycle in a thread that continuously create an HBITMAP, call a function that use this bitmap, and then delete it. At loop start, I check if the process memory usage is bigger than the previous cycle, and if it is, I print it. Using CreateBitmap() and DeleteObject() result in a small memory leak; the process memory usage increase by 4KB once in a while (sometimes every 10 seconds, sometimes nothing happens for minutes).

I tested it without calling the process function, too, and the problem is still there, so I think is due to the bitmap handling. Furthermore, I've made another test, creating the image outside the infinite loop (so I create it just one time) and processing it infite times in the loop, and no memory leak occures.

NOTE: DeleteObject() always return a value >0 (no errors).

Is it possible that the problem is related to DeleteObject() function? Is there something wrong in creating/deleting bitmap in this way?

TECH NOTES: Windows XP Borland C++ Builder 5


Is there any possibility that the bitmap is still selected in a device context somewhere? That might cause the DeleteObject to fail, although I'd expect it to return an error.


Funny how the problem is usually in the code people don't show.

Inside your process function you're selecting your bitmap within a device context, but you don't select it back out again, so when you try to delete it it's still part of a device context.

As an aside, your context isn't properly releasing either, nor are all the other objects you select into it. You have some huge memory leaks going on there. Of course you don't show us the code so can't help you with specifics.

And as a final point, I don't exactly see the reason behind creating a new bitmap over and over just to release it. You should create it outside the loop, then the device context, then select it into the device context, and just then you start your loop and clear the bitmap to begin writing on it. You'll get a huge performance increase.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜