我有以下类(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];
关于c++ - 删除 ptr 时堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518284/