1

我需要经常在 C++ 程序中创建 HBITMAP 图像,当然我需要在使用后删除这些位图。代码与此类似

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

我在一个线程中有一个无限循环,不断创建一个 HBITMAP,调用一个使用这个位图的函数,然后删除它。在循环开始时,我检查进程内存使用量是否大于前一个循环,如果是,我打印它。使用 CreateBitmap() 和 DeleteObject() 会导致少量内存泄漏;进程内存使用量偶尔会增加 4KB(有时每 10 秒一次,有时几分钟内没有任何反应)。

我也没有调用进程函数就测试了,问题依旧存在,所以我认为是由于位图处理。此外,我做了另一个测试,在无限循环之外创建图像(所以我只创建一次)并在循环中处理它无限次,并且没有发生内存泄漏。

注意:DeleteObject() 始终返回值 >0(无错误)。

问题是否可能与 DeleteObject() 函数有关?以这种方式创建/删除位图有什么问题吗?

技术说明:Windows XP Borland C++ Builder 5

4

2 回答 2

1

是否有可能仍然在某处的设备上下文中选择位图?这可能会导致 DeleteObject 失败,尽管我希望它会返回错误。

于 2011-05-17T16:38:38.187 回答
0

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.

于 2011-05-17T16:48:33.853 回答