我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
我是Windows平台上的c++程序员。我使用的是Visual Studio 2008。
我通常会在代码中出现内存泄漏。
通常我通过检查代码来发现内存泄漏,但这很麻烦,而且并不总是一种好方法。
因为我买不起付费的内存泄漏检测工具,所以我想让你们建议避免内存泄漏的最佳方法。
我想知道如何程序员可以找到内存泄漏。 是否应该遵循某种标准或过程来确保程序中没有内存泄漏?
当前回答
AddressSanitizer (ASan)是一种快速的内存错误检测器。 它可以发现C/ c++程序中的use-after-free和{heap,stack,global}-buffer溢出错误。它发现:
在free之后使用(悬空指针解引用) 堆缓冲区溢出 堆栈缓冲区溢出 全局缓冲区溢出 退货后使用 初始化顺序错误
这个工具很快。仪器程序的平均速度为~2倍。
其他回答
MTuner是一个免费的多平台内存分析、泄漏检测和分析工具,支持MSVC、GCC和Clang编译器。功能包括:
基于时间轴的内存使用历史和活动内存块 强大的内存操作过滤基于堆,内存标签,时间范围等。 SDK手动仪表与完整的源代码 通过命令行使用支持持续集成 调用堆栈树和树映射导航 更多。
用户可以通过GCC或Clang cross配置任何软件定位平台 编译器。MTuner内置对Windows、PlayStation 4和PlayStation 3平台的支持。
AddressSanitizer (ASan)是一种快速的内存错误检测器。 它可以发现C/ c++程序中的use-after-free和{heap,stack,global}-buffer溢出错误。它发现:
在free之后使用(悬空指针解引用) 堆缓冲区溢出 堆栈缓冲区溢出 全局缓冲区溢出 退货后使用 初始化顺序错误
这个工具很快。仪器程序的平均速度为~2倍。
如果使用gcc,则有gprof可用。
我想知道程序员如何发现内存泄漏
有些人使用工具,有些人做你做的事情,也可以通过同行代码审查
是否应该遵循某种标准或过程来确保程序中没有内存泄漏
对我来说:每当我创建动态分配对象时,我总是把释放代码放在后面,然后在中间填充代码。如果您确定之间的代码中不会出现异常,那么这样做是可以的。否则,我会使用try-finally(我不经常使用c++)。
有一些著名的编程技术可以帮助您将内存泄漏的风险降至最低:
if you have to do your own dynamic memory allocation, write new and delete always pairwise, and make sure the allocation/deallocation code is called pairwise avoid dynamic memory allocation if you can. For example, use vector<T> t whereever possible instead of T* t = new T[size] use "smart pointers" like boost smart pointers (http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/smart_ptr.htm) my personal favorite: make sure you have understood the concept of ownership of a pointer, and make sure that everywhere where you use pointers, you know which code entity is the owner learn which constructors / assignment operators are automatically created by the C++ compiler, and what that means if you have class that owns a pointer (or what that means if you have a class that contains a pointer to an object it does not own).
您可以使用Valgrind工具来检测内存泄漏。
此外,要找到特定函数中的漏洞,请在函数末尾使用exit(0),然后使用Valgrind运行它
`$` valgrind ./your_CPP_program