Search code examples
c++windowswinapiheap-corruption

Heap corruption when deleting ptr


I have the following class:

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);
};

With the following code:

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;
}

When exiting the application Visual Studio reports a heap corruption. I called "create" first, then "confirmed" is called, then "draw" is called and finally the deconstructor is called. The text is initialized correct, so I don't know what the problem is in this code. Could someone explain what is wrong? The heap corruption happens when "delete[] text" is called.


Solution

  • wcslen - returns number of char not including \0

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

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