I have to write a stack class template using arrays in C++ for my assignment. Here is my code.
#include <iostream>
template <typename Type>
class Stack {
private:
int top;
Type items[];
public:
Stack() { top = -1; };
~Stack() { delete[] items; };
void push(Type);
bool isEmpty() const;
Type pop();
Type peek() const;
};
int main (int argc, char *argv[]) {
Stack<double> st;
return 0;
}
template<typename Type>
void Stack<Type>::push(Type item) {
top++;
if(top == sizeof(items) / sizeof(Type)) {
Type buff[] = new Type[top];
std::copy(items,items+top,buff);
delete[] items;
items = new Type[2*top];
std::copy(buff,buff+top,items);
delete[] buff;
}
items[top] = item;
}
template<typename Type>
bool Stack<Type>::isEmpty() const {
return top == -1 ? true : false;
}
template<typename Type>
Type Stack<Type>::pop() {
//TODO
return items[top--];
}
template<typename Type>
Type Stack<Type>::peek() const{
//TODO
return items[top-1];
}
It is compiled fine using "g++ -Wall
".
When I run the program, I got this error.
*** glibc detected *** `./lab3: munmap_chunk(): invalid pointer: 0x00007fff41a3cdf8`
After trying out a bit with gdb, I found out the error arose from the line
free[] items
in the destructor.
I don't understand why freeing an array results in a memory leak ? Any clues ?