我必須使用C++中的數組編寫一個堆棧類模板以供我分配。在析構函數中釋放導致內存泄漏
Here是我的代碼:
#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];
}
它使用 「g++ -Wall
」 編譯正常,但是當我運行該程序,我得到這個錯誤:
* glibc detected *
./lab3: munmap_chunk(): invalid pointer: 0x00007fff41a3cdf8
嘗試了一下使用GDB後,我發現錯誤發生在該行:
'free[] items' in the destructor.
I不明白爲什麼釋放數組會導致內存泄漏?任何線索?
下一次你可以請有代碼在stackoverflow,所以當有人在幾個月時間發現主題,他們可以看到代碼 – EKS 2009-08-26 09:27:22