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

2021-12-30 00:00:00 c memory-leaks c++

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

相关文章