How do you detect/avoid Memory leaks in your (Unmanaged) code?(您如何检测/避免(非托管)代码中的内存泄漏?)
问题描述
在非托管 C/C++ 代码中,检测内存泄漏的最佳做法是什么?以及要避免的编码指南?(好像就这么简单;)
In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)
我们过去曾使用过一些愚蠢的方法:每次内存分配调用时计数器递增,释放时递减.程序结束时,计数器值应为零.
We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.
我知道这不是一个好方法,并且有一些问题.(例如,如果您要释放由平台 API 调用分配的内存,则您的分配计数将与您的释放计数不完全匹配.当然,我们在调用已分配内存的 API 调用时增加了计数器.)
I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)
我期待着您的经验、建议,也许还可以参考一些简化此过程的工具.
I am expecting your experiences, suggestions and maybe some references to tools which simplify this.
推荐答案
如果您的 C/C++ 代码可移植到 *nix,那么没有什么比 Valgrind.
If your C/C++ code is portable to *nix, few things are better than Valgrind.
这篇关于您如何检测/避免(非托管)代码中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您如何检测/避免(非托管)代码中的内存泄漏?
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
