我已经为我的 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/