使用valgrind

时间:2018-08-15 17:16:29

标签: c++ memory-leaks valgrind memcheck

我将在几周后开始准备面向对象的类,但是我在分配内存的概念上遇到了麻烦。现在,我只是将内存分配给堆栈的第一个节点,然后尝试取消分配它。如果有人可以帮助我发现我的析构函数在做什么错,将不胜感激。预先感谢!

我从valgrind memcheck获得的输出是:

==13653== 8 bytes in 1 blocks are still reachable in loss record 1 of 1
==13653==    at 0x4847DA4: operator new(unsigned int) (vg_replace_malloc.c:328)
==13653==    by 0x10A2B: Stack::AddNode(int) (Stack.C:25)
==13653==    by 0x10923: main (Main.C:5)
==13653==
==13653== LEAK SUMMARY:
==13653==    definitely lost: 0 bytes in 0 blocks
==13653==    indirectly lost: 0 bytes in 0 blocks
==13653==      possibly lost: 0 bytes in 0 blocks
==13653==    still reachable: 8 bytes in 1 blocks
==13653==         suppressed: 0 bytes in 0 blocks

代码:

#include <iostream>

using namespace std;

class Stack {
  private:

    struct node{
      int data;
      node * prev;
    };

    node * stackptr;

  public:

   Stack() {
     stackptr = nullptr;
   }

   ~Stack() {
      cout << "Calling destructor" << endl;
      node * p1 = stackptr;
      node * delptr = nullptr;

      while(p1 != nullptr) {
        delptr = p1;
        p1 = p1->prev;
        delptr->prev = nullptr;
        cout << "Deleteing " << delptr->data << " from the stack" << endl;
        delete delptr;
      }
   }

   void AddNode(int data) {
      node * n = new node;
      n->data = data;

      if(stackptr == nullptr) {
        stackptr = n;
        stackptr->prev = nullptr;
      }
      else {
         n->prev = stackptr;
         stackptr = n;
      }
   }
};

int main() {
  Stack s;
  s.AddNode(1);
  s.AddNode(2);
  return 0;
}

编辑:我已经完成了AddNode类。我仍然遇到类似的问题,但是现在有两次内存泄漏(两次调用main中的AddNode)。

编辑:使用C ++ 6.3.0版和valgrind 3.13.0版

0 个答案:

没有答案