c_cpp 内存泄漏样本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 内存泄漏样本相关的知识,希望对你有一定的参考价值。

#include <iostream> // std::cout, std::endl;
#include <memory>   // std::shared_ptr
#include <string>   // std::string
#include <vector>   // std::vector

class A
{
public:
  A()
  {
    std::cout << "A is created" << std::endl;
  }

  ~A()
  {
    std::cout << "A is destroyed" << std::endl;
  }
};

class B
{
public:
  B(std::string s)
    : id(s)
  {
    std::cout << "B: " << id << " is created" << std::endl;
  }

  B(const B &obj)
    : id(obj.id + "(copied)")
  {
    std::cout << "B: is copied from " << obj.id << std::endl;
  }

  ~B()
  {
    std::cout << "B: " << id << " is destroyed" << std::endl;
  }

private:
  std::string id;
};



A a[2];
/*static*/ std::vector<B> b;
/*static*/ std::vector<B*> ptr; // Memory Leak!
/*static*/ std::vector<std::shared_ptr<B>> shrPtr;

int main()
{
  std::vector<B*> ptr;
  
  // Create a B(1) and it's copied into b. 
  // The created B(1) will be destoryed after calling 
  // because its lifetime is within b.push_back().
  b.push_back(B("1"));

  // Create a B(2) and put its address into ptr.
  // Cause memory leak because there is no memory recall mechanism
  // after ptr is destroyed when the program is finished. 
  ptr.push_back(new B("2"));

  // To avoid the above case, we can use shared_ptr to manage allocated memory.
  // The reference count to B(3) will be added to 1 from 0 
  // when the share pointer to B(3) is created.
  // Upon shrPtr is destroyed, the share pointer to B(3) 
  // in the vector will also be destroyed, so the reference count to B(3) 
  // will be subtracted to 0 from 1. When the reference count equals to 0,
  // shared_ptr will deallocate the pointed address automatically.
  shrPtr.push_back(std::shared_ptr<B>(new B("3")));
  return 0;
}

以上是关于c_cpp 内存泄漏样本的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 记录deallocs的NSObject类别,在跟踪内存泄漏时非常有用

地图上的Leafletjs内存泄漏删除

音频回调线程中的内存泄漏(iOS)

ExtJS4 内存泄漏

c_cpp dlib图样本

c_cpp 样本文件