_bstr_t内存泄漏 [英] _bstr_t memory leak

查看:156
本文介绍了_bstr_t内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c ++代码.但是它不能正确释放内存.告诉我哪里错了,这是我的代码

I have a c++ code. But it is not releasing memory properly. Tell me where I am wrong, here is my code

1 void MyClass::MyFunction(void)
2 {
3    for (int i=0; i<count; i++)
4    {
5        _bstr_t xml = GetXML(i);
6        // some work
7        SysFreeString(xml);
8    }
9 }

GetXML(第5行)返回了一个BSTR.在此程序存储增加.但是在SysFreeString(第7行)之后,内存不会释放.我在这里做错了什么?

GetXML (line 5) returns me a BSTR. At this memory of program increases. But after SysFreeString (line 7) memory does not release. What I am doing wrong here?

推荐答案

首先:

// This makes a copy.
// This is where the leak is. You are leaking the original string.
_bstr_t xml = GetXML();

// You want to use this, to attach the BSTR to the _bstr_t
_bstr_t xml = _bstr_t(GetXML(), false);

第二,不要这样做:

SysFreeString(xml); 

_bstr_t类将为您做到这一点.

The _bstr_t class will do that for you.

第三,BSTR不会立即将内存释放到OS,它会缓存最近使用的字符串,以使SysAllocString更快. SysFreeString之后,您不应该期望看到内存使用率急剧下降.

Third, BSTR will not release the memory to the OS immediately, it caches recently used strings in order to make SysAllocString faster. You shouldn't expect to see memory usage go straight down after SysFreeString.

您可以出于调试目的控制此行为:

You can control this behaviour for debugging purposes:

最后,在任务管理器中查看内存使用情况时,您需要查看提交大小"列而不是工作集"列.转到菜单->查看->选择列以显示该列.还要注意,这确实只能在一段时间内提供帮助-内存可能不会立即释放到操作系统,但是如果您没有泄漏,则它不会在数小时内永久消失.

Lastly, when viewing memory usage in Task Manager you need to look at the column "Commit Size" not "Working Set". Go to Menu->View->Select Columns to show the column. And also note that this really only helps over a period of time - the memory may not be released to the OS immediately, but if you have no leaks, it shouln't go up forever, over a course of hours.

这篇关于_bstr_t内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆