Skillapop
Skillapop

Reputation: 1

Using Linked-lists to implement a stack, debug assertion failed

I am currently working on implementing a stack data structure using linked lists in C++. I can compile everything fine up until the point I test my "stack.push" method when I receive a debug assertion failed error that I have no where near enough knowledge as to how to begin to fix it. I just started on here so I cannot post images apparently, but in short it says:

Debug Assertion Failed!
Program...ual studio 2013/....~
File:f:/dd/vctools/crt/crtw32/misc/dbgdel.cpp
Line: 52
Expression:_BLOCK_TYPE_IS_VALID(pHead->nBlockUse

and here are my codes: Stack.h

#ifndef _STACK_H
#define _STACK_H

#include "LList.h"
typedef int ItemType;
class Stack{

public:
    Stack();
    ~Stack(); 

    int size() { return size_; }
    void push(ItemType x);
    ItemType pop();
    ItemType top() { return top_; }

private:
    ItemType top_;
    void copy(const Stack &source);
    int size_;
    LList items_;

};
#endif _STACK_H

stack.cpp:

#include "Stack.h"

Stack::Stack()
{
    size_ = 0;
    ItemType top_ = NULL;
}

void Stack::push(ItemType x)
{
    items_.append(x);
    size_ += 1;
    ItemType top_ = x;
}
ItemType Stack::pop()
{
    ItemType top_ = size_ - 1;
    size_ -= 1;
    return items_.pop();
}

Stack::~Stack()
{
    items_.~items_();
}

The error occurs after writing test code that assigns a stack and then tries to push a number onto the stack. Any help would be appreciated and I apologize if there are any formatting issues with my post.

Upvotes: 0

Views: 80

Answers (2)

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

There are several problems with your code:

  • Like mentioned in another answer, append will add the item at the end of the list (i.e., at the bottom from stack perspective) instead of at the top.

  • Your usage of top is inconsistent, you should decide what it means. Classically, top would hold or point to the last inserted element.

  • You have syntax issues and you're actually redeclaring a new local variable for top instead of using the class member.
  • You have memory corruption in the destructor when you explicitly call the contained list destructor.

Upvotes: 2

Lawrence Aiello
Lawrence Aiello

Reputation: 4638

You are a bit confused as to what append does. Append places a value (in this case an ItemType x) to the end of your stack, not the front. You then assign the top of the stack to the end of the stack, and you lose the pointers to the head of your list.

In fact, there are multiple things wrong now that I look at the rest of your code. I think you lack an understanding of what Linked Lists do, and you should go and read them yourself instead of me just dropping working code in my answer.

Upvotes: 1

Related Questions