I am writing a Stack template. The stack is declared as an array.
[
template <typename T, size_t N>; // N is 100
class TStack
{
...
private:
T data_[N];
...
}
I have several functions in this class template, Pop() //removes last item of stack, Push() //pushes an item to the stack, Size() //returns the size of the stack, Capacity()// returns N
I have a cpp program that tests the functionality of my template using a menu interface. When I choose Pop() without pushing anything to the stack, I get a Bus Error(core dumped).
[
template <typename T, size_t N>
... ::Pop()
{
if (size_ == 0) {std::cerr << "Stack is empty'\n'";}
else {return data_[size_-1];} //size_ is initialized to 0 and incremented when item are pushed to the stack and decremented when they are popped
}
]
When I Push() an item to the stack and then choose Pop(), it does what is expected.
What should I do to data_ to ensure that this does not happen. I understand that the Bus Error is a segmentation fault and it happens because I am trying to acces a value that is not allocated memory, but am not sure how to fix it in this situation. In the guidelines I am not allowed to use operator new or delete to insure allocation.
Thanks in advance.
[
template <typename T, size_t N>; // N is 100
class TStack
{
...
private:
T data_[N];
...
}
I have several functions in this class template, Pop() //removes last item of stack, Push() //pushes an item to the stack, Size() //returns the size of the stack, Capacity()// returns N
I have a cpp program that tests the functionality of my template using a menu interface. When I choose Pop() without pushing anything to the stack, I get a Bus Error(core dumped).
[
template <typename T, size_t N>
... ::Pop()
{
if (size_ == 0) {std::cerr << "Stack is empty'\n'";}
else {return data_[size_-1];} //size_ is initialized to 0 and incremented when item are pushed to the stack and decremented when they are popped
}
]
When I Push() an item to the stack and then choose Pop(), it does what is expected.
What should I do to data_ to ensure that this does not happen. I understand that the Bus Error is a segmentation fault and it happens because I am trying to acces a value that is not allocated memory, but am not sure how to fix it in this situation. In the guidelines I am not allowed to use operator new or delete to insure allocation.
Thanks in advance.
Comment