c++ - 删除 ptr 时堆损坏

标签 c++ windows winapi heap-corruption

我有以下类(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);
};

使用以下代码:

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 报告堆损坏。我先调用了“create”,然后调用了“confirmed”,然后调用了“draw”,最后调用了解构函数。文本初始化正确,所以我不知道这段代码有什么问题。有人可以解释什么是错的吗?调用“delete[] text”时会发生堆损坏。

最佳答案

wcslen - 返回不包括\0 的字符数

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

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

关于c++ - 删除 ptr 时堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518284/

相关文章:

java - Linux,java.lang.UnsatisfiedLinkError : no "library file" in java. library.path

c++ - 将 typedef 作为类的非静态成员访问?

python - 为什么python subprocess.Popen通过cmd.exe启动一个子进程?

windows - 为所有浏览器嵌入播放器

linux - 在 Windows 的 samba 导出的 linux 目录上创建符号链接(symbolic link)

winapi - 使用 Win32 API 的 Windows "real"用户列表

windows - 如何使文件系统缓存失效?

c++ - 取消引用指针的程序集

c++ - Visual Studio 中的 "Create Precompiled Header"(/Yc) 和 "Use Precompiled Header"(/Yu) 有什么区别?

c++ - 在同一个 DLL 中使用 _COM_SMARTPTR CreateInstance 而无需注册