删除ptr时堆损坏

Heap corruption when deleting ptr

本文关键字:损坏 ptr 删除      更新时间:2023-10-16

我有以下类:

class Label : public Object
{
public:
    Label ();
    ~Label ();
    void create (const unsigned int x, const unsigned int y, const wchar_t* text);
    void destroy ();
private:
    unsigned int x, y;
    wchar_t* text;
    void draw (HDC hdc);
    void confirmed (ObjectManager* m);
};

,代码如下:

Label::Label ()
{
    type = LABEL;
    text = NULL;
}
Label::~Label ()
{
    destroy ();
}
void Label::create (const unsigned int x, const unsigned int y, const wchar_t* text)
{
    unsigned int len = wcslen (text);
    this->x = x;
    this->y = y;
    this->text = new wchar_t[len];
    wcscpy (this->text, text);
}
void Label::destroy ()
{
    if (text) {
        delete[] text;
        text = NULL;
    }
    if (m) {
        m->remove (this);
        m = NULL;
    }
}
void Label::draw (HDC hdc)
{
    if (text)
        TextOut (hdc, x, y, text, wcslen (text));
}
void Label::confirmed (ObjectManager* m)
{
    this->m = m;
}

退出应用程序时,Visual Studio报告堆损坏。我首先调用"创建",然后调用"确认",然后调用"绘制",最后调用解构器。文本初始化正确,所以我不知道这个代码中的问题是什么。有人能解释一下是怎么回事吗?当调用"delete[] text"时,会发生堆损坏。

wcslen -返回不包括的字符个数

unsigned int len = wcslen (text);
this->text = new wchar_t[len + 1];

见http://www.cplusplus.com/reference/cwchar/wcslen/