user2999870
user2999870

Reputation: 375

C++ Memory leak error when implementing Stack class

I was implementing a Stack class and when I tried to call push(), I received a memory leak error (double free or corruption(fasttop)). Here is my code:

#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;
  }
}

I debugged and traced it to:

   temp = curr;

I cannot see any other way of implementing the push() method. My StackNode only contains a default constructor which sets the pointer prev to NULL. Any help would be appreciated. Thanks!

Edit: Here is my StackNode:

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

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

And here is my main:

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

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

Upvotes: 0

Views: 192

Answers (1)

Destiny
Destiny

Reputation: 506

I have three questions.

  1. Stack::pop

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

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

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

Upvotes: 1

Related Questions