删除ptr时堆坏了

时间:2014-07-01 19:55:59

标签: c++ windows winapi heap-corruption

我有以下课程:

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会报告堆损坏。我打电话给#34;创建"首先,然后"确认"被叫,然后"画"被调用,最后调用解构函数。文本初始化正确,因此我不知道此代码中的问题是什么。有人可以解释什么是错的吗?当" delete [] text"被称为。

1 个答案:

答案 0 :(得分:6)

wcslen - 返回不包括\ 0

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

请参阅http://www.cplusplus.com/reference/cwchar/wcslen/