在 C/C++ 中避免内存泄漏的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2983216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ways to avoid Memory Leaks in C/C++
提问by Ankur
What are some tips I can use to avoid memory leaks in my applications? In my current project I use a tool "INSURE++" which finds the memory leak and generate the report.
我可以使用哪些技巧来避免应用程序中的内存泄漏?在我当前的项目中,我使用一个工具“INSURE++”来查找内存泄漏并生成报告。
Apart from the tool is there any method to identify memory leaks and overcome it.
除了该工具之外,还有什么方法可以识别内存泄漏并克服它。
回答by fmark
There are three main ways of doing this.
有三种主要方法可以做到这一点。
The first is to not create memory leaksin the first place. Defensive programming techniques are invaluable here. See this excellent presentationfor a summary of this issues, or the relevant chapter in Secure C Coding. I am more familiar with C than C++, but I understand that C++'s smart pointersare useful here.
首先是首先不要造成内存泄漏。防御性编程技术在这里是无价的。有关此问题的摘要,请参阅此优秀演示文稿,或Secure C Coding 中的相关章节。我比 C++ 更熟悉 C,但我知道 C++ 的智能指针在这里很有用。
A second approach static analysis, which attempts to detect errors in your source-code. The original tool in this category is lint, which is now sadly outdated. The best tools, as far as I know, are commercial such as coverty. However, some free tools do exist.
第二种方法静态分析,它尝试检测源代码中的错误。此类别中的原始工具是lint,现在可悲的是已经过时了。据我所知,最好的工具是商业性的,例如coverty。但是,确实存在一些免费工具。
The third approach is to detect memory leaks at runtime, like INSURE++does. Valgrindis excellent here and highly recommended. It may help catch bugs you've already introduced. It is especially helpful if you do have a test suite that has good code coverage.
第三种方法是在运行时检测内存泄漏,就像INSURE++那样。 Valgrind在这里非常棒,强烈推荐。它可能有助于捕获您已经引入的错误。如果您确实有一个具有良好代码覆盖率的测试套件,这将特别有用。
回答by Secure
For C, a good code organization helps. I.e. don't throw calls to malloc() and free() all over your codebase. Centralize them into two functions, then you have one single point for all the checkings. The simplest one could be to count the successful calls and check at program exit that they are balanced.
对于 C,良好的代码组织会有所帮助。即不要在你的代码库中抛出对 malloc() 和 free() 的调用。将它们集中到两个函数中,然后您就可以通过一个点来进行所有检查。最简单的方法是计算成功调用并在程序退出时检查它们是否平衡。
static unsigned long mymem_count_alloc = 0;
static unsigned long mymem_count_free = 0;
void *mymem_alloc (size_t size)
{
void *p;
p = malloc(size);
if (p)
{
mymem_count_alloc++;
}
else
error logging/handling/signaling
return (p);
}
void mymem_free (void *p)
{
if (p)
{
free(p);
mymem_count_free++;
}
}
void mymem_check (void)
{
if (mymem_count_alloc != mymem_count_free)
error alert
}
You can continue this for the different data structures. Whereever you need to allocate memory for a string, use mystr_alloc and mystr_free. And so on. When a leak is detected this way, you can quickly narrow it down.
您可以针对不同的数据结构继续此操作。无论您需要在何处为字符串分配内存,都可以使用 mystr_alloc 和 mystr_free。等等。当通过这种方式检测到泄漏时,您可以快速缩小范围。
回答by HostileFork says dont trust SE
Smart pointers can be very helpful in automating the bookkeeping of object lifetimes:
智能指针在自动记录对象生命周期方面非常有帮助:
http://ootips.org/yonat/4dev/smart-pointers.html
http://ootips.org/yonat/4dev/smart-pointers.html
Where possible, use stack allocated objects inside of their relevant scopes instead of new/delete.
在可能的情况下,在相关范围内使用堆栈分配的对象,而不是新建/删除。
Tools like valgrind have some overhead and can slow down your runs. If you know your codebase and the kinds of leaks that tend to arise, you can target specific classes and implement lighter weight checks (even just a simple object count that you check against zero when you quit). These lightweight checks can then be used to motivate you into doing a more extensive valgrind debugging session when they are triggered.
像 valgrind 这样的工具有一些开销,会减慢你的运行速度。如果你知道你的代码库和容易出现的泄漏类型,你可以针对特定的类并实现更轻的重量检查(甚至只是一个简单的对象计数,当你退出时检查为零)。然后,这些轻量级检查可用于激励您在触发时进行更广泛的 valgrind 调试会话。
回答by DVK
Are we talking tools to find leaks, or ways to code to avoid them?
我们是在谈论寻找泄漏的工具,还是通过编码来避免泄漏的方法?
For the former, the above mentioned valgrind, or Rational suite of IBM tools if you have a license to that. Dr. Dobbs recommended CompuWare's BoundsChecker but that was 2002.
对于前者,上面提到的 valgrind 或 IBM 工具的 Rational 套件,如果您有许可证的话。Dobbs 博士推荐了 CompuWare 的 BoundsChecker,但那是 2002 年。
For the later, see:
后面的请看:
C++ idiom to avoid memory leaks?
http://www.cprogramming.com/tutorial/memory_debugging_parallel_inspector.html
http://www.cprogramming.com/tutorial/memory_debugging_parallel_inspector.html
http://scottmcpeak.com/memory-errors/
http://scottmcpeak.com/memory-errors/
http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
http://www.yolinux.com/TUTORIALS/C++MemoryCorruptionAndMemoryLeaks.html
回答by Billy ONeal
Use a smart pointer, such as std::shared_ptr<t>
(C++0x), std::tr1::shared_ptr<t>
(TR1), or boost::shared_ptr<t>
. Of course this solution only works with C++ -- you're on your own in C.
使用智能指针,例如std::shared_ptr<t>
(C++0x)、std::tr1::shared_ptr<t>
(TR1) 或boost::shared_ptr<t>
. 当然,这个解决方案只适用于 C++——你在 C 语言中是自己的。
回答by ShinTakezou
To avoid or to detect? To avoid, first detect and try to understand where and why... Another way could be the use of a GC library, like the one described here, but other (maybe better) libraries may exist.
逃避还是发现?为了避免,首先检测并尝试了解在哪里以及为什么......另一种方法可能是使用 GC 库,就像这里描述的那样,但可能存在其他(可能更好)的库。