gpt4 book ai didi

c++ - 删除 ptr 时堆损坏

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:23 25 4
gpt4 key购买 nike

我有以下类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com