As an exorcise I'm trying to implement a Stack from scratch.
When testing the class the push method always crashes the process and rarely at the same point twice in a row. Sometimes it will run for several iterations of pushing a value onto the stack, others it won't make it passed the first.
Class definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template< class T>
class Stack {
public:
bool isEmpty();
size_t size();
T pop();
void push(T item);
Stack();
Stack(const Stack<T>& cpy);
~Stack();
T peek();
private:
T* stack;
size_t top;
};
constructor:
1 2 3 4
template< class T >
Stack<T>::Stack() {
top = 0;
}
Detor code:
1 2 3 4 5
template< class T >
Stack<T>::~Stack() {
delete[] stack;
stack = NULL;
}
Initially I was just deleting stack and assigning tmp to stack. But, at some point I thought I might be corrupting the heap and went on a wild goose chase introducing more bugs with each test :P
Also when I tried to catch bad_alloc during testing it never actually threw an exception.
Lol, did I mention this exercise was because I haven't really used C/C++ in a little over a year? Kinda rusty :P