0

I want to write my own version of stack, this is what I have:

template<class myStackType> class myStackClass
{
    myStackType array[1000];
    int size;
public:
    myStackClass()
    {
        size = 0;
    }
    void pop()
    {
        size--;
    }
    void push(myStackType a)
    {
        array[size] = a;
        size++;
    }
    myStackType top()
    {
        return array[size-1];
    }
    bool empty()
    {
        return(size == 0);
    }
};

but when I try to actually use it

struct grade
{    
    int mid;
    int final;
    string name;
    grade(int mid1 = 0, int final1 = 0, string name1 = 0)
    {
        mid = mid1;
        final = final1;
        name = name1;
    }
};

myStackClass<grade> myStack;

I get a debug assertion failed: invalid null pointer

on the other hand, the std::stack works just fine in the same spot with the same data type

what am I doing wrong?

Thanks!

1
  • if I'm not wrong the stack grows as the user inserts more and more. why did you make it have maximum 1000 elements? Commented Oct 23, 2013 at 19:06

2 Answers 2

2

This is wrong:

string name1 = 0

It tries to construct a string from a const char* which is 0 - and this is not allowed. You probably meant:

string name1 = ""
Sign up to request clarification or add additional context in comments.

Comments

1

You are assigning 0 to a string in your constructor. That's the bug. The compiler is trying to interpret the 0 as a char *, i. e. a C-style string. But since it's a 0, it is interpreted as a NULL pointer.

You may also want to do some error checking to make sure your stack doesn't overflow, or that you don't try to pop off an empty stack.

2 Comments

That was it, thanks - although now I am confused why it worked with std::stack instead of mine.. oh well, thanks
That depends on how the stack class allocates its storage. If std::stack is using a T* it does not need to actually allocate any T in its constructor. Yours is using an array, so if I remember correctly, every element in the storage is going to be initialized, T() is going to be called, and, yes, then the string = nullptr is going to happen and crash ensues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.