c++ - Stack 析构函数中的双重释放或损坏

标签 c++ g++

我很确定问题出在 while (!empty()) pop(); 上,因为在我将其注释掉之后。一切正常。但它不会delete head。这部分有什么问题?

意图如下:LinkedList有两个数据成员,headtail。当列表为空时,它们都应等于 0。当列表非空时,headtail 都应该是非零的,并且它们应该分别引用列表中的第一项和最后一项。并且应该有一条从 headtail 的路径,通过 next_ 指针。如果列表只有一项,则 head == tail

#include <iostream>
//stack using linked list
class LinkedList {
 public:
  LinkedList() : head(0), tail(0) {}
  ~LinkedList() {
    while (!empty()) pop();
    std::cout<< "~LinkedList" << std::endl;
  }
  void pop() {
    node* temp;
    temp = head;
    for ( ; temp->next_ != 0; temp = temp->next_) {
      tail = temp;
    } 
    delete temp; 
    tail->next_ = 0;
    std::cout << "pop()" << std::endl;
  } //removes, but does not return, the top element
  int top() {
    return tail->value_;
  } //returns, but does not remove, the top element
  bool empty() {
    return head == 0;
  }
  void push(const int& value) {
    node* element = new node(value);
    if (empty()) {
      head = tail = element;
    } else {
      tail->next_ = element;
      tail = element;
    }
  } //place a new top element
 private:
  class node {
   public:
    node(const int& input) : value_(input), next_(0) {};
    int value_; //store value
    node* next_; //link to the next element
  };
  node* head;
  node* tail;
};
int main() {
  LinkedList list;
  list.push(1);
  list.push(2);
  std::cout << list.top() << std::endl;
  list.pop();
  std::cout << list.top() << std::endl;
  return 0;
}

通过将析构函数更改为以下代码来解决问题:

  ~LinkedList() {
    while (head != tail) pop();
    delete head;
    std::cout<< "~LinkedList" << std::endl;
  }

最佳答案

你这里有一部分问题

bool empty() {
    return head == 0;
}

什么时候 head 设置为 0 (NULL)?从来没有?

关于c++ - Stack 析构函数中的双重释放或损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046495/

相关文章:

c++ - sse2 向量化和虚拟机

c++ - 如何让 g++ 对未使用的成员变量发出警告

C++ 私有(private)函数 - 不在此范围内错误

c++ - Makefile:将 llvm 程序编译为 g++ 编译的 bnfc 项目的一部分

c++ - 为什么我在链接期间得到 "undefined reference to ` glibtop_init'"?

c++ - 如何强制 g++ 只编译 c++11 标准?

c++ - 函数指针作为类方法声明中的参数

c++ - 碳化物 C++ symbian 编译器错误

c++ - 将字符缓冲区转换为结构

c++ - 获取长 double vector 的方差