为什么此代码会泄漏内存?(出论点和指针)
Why does this code leak memory? (Out arguments and pointers)
我是C++新手。 我编写此方法是为了轮询加速度计。 它被反复调用,并泄漏内存。
AccelSample SensorObj::GetReport() {
ISensorDataReport* pReport;
HRESULT hr = pSensor->GetData(&pReport);
// theoretically, i would fill this struct with the values from pReport, but this is just here for testing.
AccelSample sample;
sample.x = 0;
sample.y = 0;
sample.z = 0;
sample.timestamp = 0;
return sample;
}
行
HRESULT hr = pSensor->GetData(&pReport);
似乎是泄漏的来源。 如果我把它注释掉,就没有泄漏。 GetData 的定义是
virtual HRESULT STDMETHODCALLTYPE GetData(__RPC__deref_out_opt ISensorDataReport **ppDataReport) = 0;
此 API 的文档显示 GetData 的调用方式相同。https://msdn.microsoft.com/en-us/library/windows/desktop/dd318962%28v=vs.85%29.aspx
如果我理解正确,GetData 会取出一个指向指针的指针的 out 参数。 通过将 &pReport 传递给它,我传递了指针 pReport 的"地址"。 是吗? 这不应该没问题吗?
编辑:我应该提到我尝试过"删除pReport"。 我收到一个错误,说"调试断言失败。_BLOCK_TYPE_IS_VALID(pHead->nBlockUse".
此代码违反了 COM 的引用计数机制,并且当您只有一个对对象的引用时工作正常:
delete pReport
通常,您应该调用发布方法或使用 CComPtr 智能指针:
CComPtr<ISensorDataReport> pReport;
HRESULT hr = pSensor->GetData(&pReport);
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 如何防止C++遗留代码中的挂起指针
- 理解这行C++指针代码
- 为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?
- 为什么我的代码在指针方面停止运行?
- 以下与指针相关的代码的输出是什么?
- C++指针问题:如何修复这些代码中的错误?
- 如何使用指针直接从托管代码中的非托管代码中读取矢量数据
- 为什么下面的代码段返回指针指向的值而不是指针的地址?
- 使用指针向量(带代码)C++(以及对其使用的便利性的怀疑)时出现问题
- 为什么从 constexpr 引用生成的程序集代码与从 constexpr 指针生成的程序集代码不同?
- 由于指针算法错误,代码在 memcpy 中崩溃
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- 使用指针编译代码后,.cpp文件将变为随机字符
- OpenCV如何处理Mat作为指针来加速代码
- 我的指针代码 c++ 中的分段错误(核心转储)
- 这两个指针代码有什么区别
- 由于没有明显的原因,请继续在C 的指针代码上遇到错误
- C++:传递和返回指向数组的指针-代码不起作用
- 如何将 Visual Studio 配置为在调试时'skip'智能指针代码?