【问题标题】:vector pointer causing valgrind memory leak导致 valgrind 内存泄漏的向量指针
【发布时间】:2012-02-16 22:49:04
【问题描述】:

我正在尝试学习 C++ 和 valgrind。所以我写了下面的代码来测试一下。但我得到了一些内存泄漏。谁能解释导致内存泄漏的原因?提前致谢。

#include <vector>
#include <iostream>
using namespace std;

class test
{
     int c;
      public:
      void whatever();
}; 
void test:: whatever()
{
     vector<test*> a;
     if(true)
     {
           test* b = new test();
           b->c = 1;
           a.push_back(b);
     }
     test* d = a.back();
     cout << "prints: " << d->c;
     delete d;
}

int main()
{
    test* a = new test();
    a->whatever();
    return 1;
}

来自 valgrind

==28548== HEAP SUMMARY:
==28548==     in use at exit: 4 bytes in 1 blocks
==28548==   total heap usage: 3 allocs, 2 frees, 16 bytes allocated
==28548==
==28548== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==28548==    at 0x4C27CC1: operator new(unsigned long) (vg_replace_malloc.c:261)
==28548==    by 0x400C36: main (in a.out)
==28548==
==28548== LEAK SUMMARY:
==28548==    definitely lost: 4 bytes in 1 blocks
==28548==    indirectly lost: 0 bytes in 0 blocks
==28548==      possibly lost: 0 bytes in 0 blocks
==28548==    still reachable: 0 bytes in 0 blocks
==28548==         suppressed: 0 bytes in 0 blocks
==28548==
==28548== For counts of detected and suppressed errors, rerun with: -v
==28548== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)

我是不允许从指针的副本中删除还是我做错了什么?

【问题讨论】:

    标签: c++ valgrind


    【解决方案1】:

    您永远不会在a 上致电delete

    当然,这里重要的一点是您使用的是vector 指针。你到底为什么要这样做?让向量为您处理内存管理!

    【讨论】:

      【解决方案2】:

      您忘记在main() 末尾添加delete a;

      请注意,您编写的所有内容都应该永远进入实际代码。你不应该使用动态分配 (new),除非你绝对必须知道为什么。


      假设你想维护指针向量用于教育目的,那么这里有一个更好的写法:

      #include <vector>
      #include <memory>  // for unique_ptr
      
      // intentionally left blank; NO abusing namespace std!
      
      struct Foo
      {
          int c;
      
          void whatever()
          {
              std::vector<std::unique_ptr<test>> v;
      
              if (true)
              {
                  v.emplace_back(new test);
                  v.back()->c = 1;
              }
      
              // everything is cleaned up automagically
          }
      };
      
      int main()
      {
          Test a;        // automatic, not dynamic
          a.whatever();
      
          return 1;
      }
      

      这仍然只是为了教育目的;在现实生活中,您会非常努力地使用普通的std::vector&lt;test&gt;,因为vector已经是一个动态数据结构,几乎不需要额外的间接级别。

      【讨论】:

      • 感谢您的回答。对我这种初学者真的很有帮助。但是,如果由于外部函数需要传递指针,会发生什么?可以使用向量/指针数组还是有更好的解决方案推荐?
      • @oliten: 你可以使用地址运算符&amp; :-)
      • @oliten: some_func(&amp;vec[index]);
      【解决方案3】:

      内存泄漏在 main.js 中。您没有删除分配的 test 对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-10
        • 1970-01-01
        • 2019-04-18
        • 2021-04-20
        • 1970-01-01
        • 2021-06-14
        • 2013-03-14
        • 1970-01-01
        相关资源
        最近更新 更多