最常见的内存/资源泄漏错误 [英] Most Common Memory/Resource Leak Errors

查看:76
本文介绍了最常见的内存/资源泄漏错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有好的C ++程序员都知道如何避免泄露内存(或像套接字那样的资源):

All good C++ programmers know how to avoid leaking memory (or resources like sockets):


  1. 始终使用智能指针, e .: std :: auto_ptr boost :: shared_ptr


但是,内存泄漏仍然会发生。指出在程序中发现
a内存泄漏时最常见的问题,即使您使用了上述技术。

But, memory leaks still happen. Point most common issues when you discovered a memory leak in a program, even when you used the above techniques.

我开始:

有时您忘记将基类的析构函数定义为虚拟。所以所有派生类都是通过指针引用的基类,没有被正确销毁,因此泄漏。

Sometimes you forget to define a destructor of base class as virtual. So all derived classes referred by pointer to the base class which was not destroyed properly and therefore leaked.

推荐答案

的错误比只是泄漏。从最坏到最好:

There are many more types of errors than just leaks. In order from worst to best:

数据存储到一个区域, t。

Data is stored to an area where it shouldn't. This results in both the majority of security problems and is by far the hardest to track down.


  • 随机的位置损坏

    • 数据存储到用户可以控制的存储位置。

    • 数据存储到数组, $ $

    • X 派生的类型的对象存储到为 X ,并且 X 的大小大于其基础的大小。

    • "Random location" corruption
      • Data is stored to a memory location that the user can control.
      • Data is stored to an array without checking the indices.
      • An object of a type derived from X is stored to an array element reserved for a base type of X, and the size of X is greater than the size of its base.

      • 数据在释放后存储到内存位置。

      • 使用不正确的释放方法(不匹配导致 / 免费 malloc / delete

      • delete c> free 在同一指针上调用两次。

      • Data is store to a memory location after it is freed.
      • Incorrect method of freeing is used (mismatch resulting in new/free, malloc/delete)
      • delete or free is called twice on the same pointer.

      程序不再使用的内存仍保留。

      Memory no longer in use by the program remains allocated.


      • 使用不正确的释放方法:不匹配导致 new [] / delete c $ c> new [] / delete []

      • 内存不会自动释放在引用计数方案中的循环引用,例如当 smart_ptr 用于循环数据结构而不注意使用 weak_ptr 为循环链接。

      • 由于指针丢失,内存不被释放 - 调用free之前清除了内存的最后一个指针,因此没有办法释放它

      • 由于未正确识别其中包含的数据不再需要,因此内存不会被释放。一个例子是用于某些临时任务的静态缓存永远不会被清除。

      • Incorrect method of freeing is used: mismatch resulting in new[]/delete instead of new[]/delete[].
      • Memory is not automatically release because of a circular reference in a reference counting scheme, such as can happen when smart_ptr is used in a circular data structure without attention to using weak_ptr for the circular link.
      • Memory is not freed due to a lost pointer - the last pointer to the memory was cleared before free was called, so there is no way to release it.
      • Memory is not freed due to not properly identifying when the data it contains is no longer needed. An example is a static cache used for some temporary task is never cleared out.

      这篇关于最常见的内存/资源泄漏错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆