c++ - 检测到堆损坏 : after Normal block(#151) at 0x00DB4E70

标签 c++ visual-studio memory-management

我已经为我的 Word 类实现了一个列表,并且在程序试图删除我的列表时检测到堆损坏。它在析构函数中进入循环并删除第一个元素,然后当他第二次进入时,并试图破坏"new"头,我得到堆损坏错误。我不明白为什么会出错。任何帮助将不胜感激。

Word.h:

#include <cstring>
class Word
{
protected:
  char* word;
  char* type;
public:
  Word();
  Word(char );
  Word(char *);
  Word(char *, int);
  Word(const Word&);

  Word& operator=(const Word &);

  void setWord(char);
  void setWord(char *);
  void setWord(char*, int);

  void setType(char);
  void setType(char*);
  void setType(char*, int);

  ~Word();
};

WordList.h:

#include "Word.h"
#include <cstdlib>

class WordList
{
public:
 struct Node
 {
    Word data;
    Node  *next, *prev;
    //~Node();
 };
 Node *head;
 Node *tail;
 WordList();
 ~WordList();
 void add(Word &d);

};

WordList.cpp:

#include "WordList.h"


WordList::WordList(void)
{
head = nullptr;
tail = nullptr;
}

WordList::~WordList(void)
{
   while(head != nullptr)
   {
    Node *n = head->prev;
    delete head;
    head = n;
   }
}

void WordList::add(Word &d)
{
  Node *n = new Node;
  n->data = d;   // I overload =, and it copies information from d to data
  n->next = head; 
  if (head!=nullptr)
    head->prev = n;
  if(head == nullptr){
    head = n;
    tail = head;
  } else 
    head = n;
}

最佳答案

在析构函数中

 Node *n = head->prev;

需要

 Node *n = head->next;

如果您关注添加方法,您会发现您从未将 n 设置为 prev 值,因此 head->prev 具有与 n->prev 相同的值,您从未设置过(为 null),使 head->prev 具有垃圾值,删除它地址不会很漂亮。

关于c++ - 检测到堆损坏 : after Normal block(#151) at 0x00DB4E70,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132705/

相关文章:

c++ - 是否可以自动序列化 C++ 对象?

c# - 更改实现接口(interface)模板

c# - Visual Studio 2015 测试运行器中的 "The handle is invalid"异常

qt - 当动态创建的对象有父对象时,QML 不会释放大量内存

linux - libc内存管理

c++ - 在 C++ 中抓取递归 ntfs 目录的最快方法

android - 内存不足会导致 native 代码出现段错误吗?

ios - 从 VS 调试 iOS 时,程序 'Mono' 已退出,代码为 0 (0x0)

c++ - 如果我使用 std::function 来捕获 lambda,我是否应该担心它被释放?

c++ - LNK2019 : unresolved external symbol; foreach. h FE_Iterator()