cparks10
cparks10

Reputation: 377

Template Stack not pushing?

I keep getting a segmentation fault and am not sure why. Pretty new to templates and am just messing around trying to figure things out. I built a stack using a template, and have only incorporated the member functions push and top/peek so far. Trying to create a string stack.

#include <iostream>
#include <string>

template <class T>
class TemplateStack {
public:
    typedef T type;

    TemplateStack()//Default Constructor taking no parameters
    {
        max_size_ = 50;
        TopOfStack = 0;
    } 

    void push(T element)
    {
        if (TopOfStack == max_size_)
            throw string("Stack's underlying storage is overflow");
        TopOfStack++;
        data_[TopOfStack] = element;
    }

      T top() {
            if (TopOfStack == -1)
                  throw string("Stack is empty");
            return data_[TopOfStack];
      } 

private:
    size_t TopOfStack; //Generic data type for the top element of stack
    size_t max_size_;
    T* data_;
};



int Main (){
    TemplateStack <string> T;   
    T.push("Hello");
    T.push("World!");
    std::cout<<T.top()<<std::endl;
    return 0;
};

Upvotes: 2

Views: 63

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

You did not allocate memory for the data member

T* data_;

in the constructor

TemplateStack()//Default Constructor taking no parameters
{
    max_size_ = 50;
    TopOfStack = 0;
} 

So any operation with the stack that uses the pointer results in undefined behavior.

And the initial value of the data member TopOfStack according to the implementation of other methods shall be -1.

I think you mean at least

TemplateStack()//Default Constructor taking no parameters
{
    max_size_ = 50;
    TopOfStack = -1;
    data_ = new T[max_size];
} 

If so you need also to write a destructor to free allocated memory.

And the method push shall check another condition

void push(T element)
{
    if (TopOfStack + 1 == max_size_)
        throw string("Stack's underlying storage is overflow");
    TopOfStack++;
    data_[TopOfStack] = element;
}

Or as the data member TopOfStack has the type size_t then you could write

TemplateStack()//Default Constructor taking no parameters
{
    max_size_ = 50;
    TopOfStack = 0;
    data_ = new T[max_size];
} 

void push(T element)
{
    if (TopOfStack == max_size_)
        throw string("Stack's underlying storage is overflow");
    data_[TopOfStack++] = element;
}

and

  T top() {
        if (TopOfStack == 0)
              throw string("Stack is empty");
        return data_[TopOfStack -1];
  } 

Upvotes: 4

Related Questions