您如何检测/避免(非托管)代码中的内存泄漏?

2023-09-26C/C++开发问题
3

本文介绍了您如何检测/避免(非托管)代码中的内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在非托管 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.

这篇关于您如何检测/避免(非托管)代码中的内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6