实现Stack类时C ++内存泄漏错误

时间:2017-09-08 01:34:37

标签: c++ pointers memory-leaks stack

我正在实现一个Stack类,当我尝试调用push()时,我收到了内存泄漏错误(双重释放或损坏(fasttop))。 这是我的代码:

#include "StackNode.h"
#include "Stack.h"
#include <iostream>
using namespace std;

Stack::Stack(){
  curr = NULL;   
}

Stack::~Stack(){
  while(!empty())
    pop();
  delete curr;
}

bool Stack::empty(){
  return curr==NULL;
}

int Stack::top(){
  return curr->value;
}

void Stack::push(int a){
  StackNode * temp = new StackNode;
  temp->value = a;

  if (!empty())        // atleast 1 element
  temp->prev = curr;   // temp links to current

   curr = temp;        // current becomes temp
}

void Stack::pop(){
  if (!empty()){
  StackNode * temp = curr;
  curr->prev = curr;
  delete temp;
  }
}

我调试并追溯到:

   temp = curr;

我看不到任何其他实现push()方法的方法。我的StackNode只包含一个默认构造函数,它将指针上一页设置为 NULL 。任何帮助,将不胜感激。谢谢!

编辑:这是我的StackNode:

#include "StackNode.h"
#include <iostream>
using namespace std;

StackNode::StackNode(){
   prev = NULL;
}

这是我的主要内容:

#include <iostream>
#include "Stack.h"
using namespace std;

int main(){
  //  Stack s;
    s.push(1);
  // cout<<s.top()<<endl;
  cout<<"pass"<<endl;
  return 0;
}

1 个答案:

答案 0 :(得分:1)

我有三个问题。

  1. 堆栈弹出::

    void Stack::pop(){
        if (!empty()){
        StackNode * temp = curr;
        curr->prev = curr;         // curr = curr->prev ?
        delete temp;
      }
    }
    
  2. 堆栈::〜堆栈

    Stack::~Stack(){
      while(!empty())
        pop();
      delete curr;                 // Why delete curr here?
    }
    
  3. 堆栈::推

    void Stack::push(int a){
      StackNode * temp = new StackNode;
      temp->value = a;             // temp->prev assign NULL ?
    
      if (!empty())
        temp->prev = curr;
    
        curr = temp;
    }