析构函数中的释放导致内存泄漏

Thu*_*ura 2 c++

我必须使用C++中的数组编写一个堆栈类模板.

是我的代码:

#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];
}
Run Code Online (Sandbox Code Playgroud)

它使用" g++ -Wall" 编译好,但是当我运行程序时,我收到了这个错误:

*检测到glibc* ./lab3: munmap_chunk(): invalid pointer: 0x00007fff41a3cdf8

在尝试使用GDB之后,我发现错误来自该行:

'free[] items' in the destructor.
Run Code Online (Sandbox Code Playgroud)

我不明白为什么释放数组会导致内存泄漏?有线索吗?

unw*_*ind 6

你应该只有delete[]你明确分配的内容new[].您的items成员不是动态分配的数组,因此您不能像它那样释放它.

另一方面,你有

Type items[];
Run Code Online (Sandbox Code Playgroud)

它实际上并没有在堆栈的对象实例中分配任何空间.