gpt4 book ai didi

c++ - 错误 : Heap block at X modified

转载 作者:行者123 更新时间:2023-11-28 00:19:48 25 4
gpt4 key购买 nike

我试图对结构使用析构函数。但是,编译器报错 Heap block at 006651F8 modified at 00665229 past requested size of 29 gift1.exe 已触发断点。

    #include "stdafx.h"

struct Node{
char *name;
int age;

Node(char *n = 0, int a = 0){
this->name = _strdup(n);
age = a;
}

~Node(){
if (this->name != 0)
delete[] this->name;
}
};

int _tmain(int argc, _TCHAR* argv[])
{

Node node1("Andy", 20);
return 0;
}

我可以知道哪里出了问题吗?

如果我使用 name 而不是 this->name 有关系吗?

附加组件:

即使我按照下面的答案将其更改为 free(this->name);,也会出现相同的错误。 00EA68D8 处的堆 block 在 00EA6909 处修改,过去请求的大小为 29 gift1.exe 已触发断点。

最佳答案

_strdup在内部使用 malloc():

The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space.

但你正在使用 delete[]释放:

Deallocates storage previously allocated by a matching operator new... If the pointer passed to the standard library deallocation function was not obtained from the corresponding standard library allocation function, the behavior is undefined.

要解决,请使用 std::string 而不是 char*(或者如果您确实不能使用 std::string,请使用 free() 并防止复制或为 Node 实现复制)。

关于c++ - 错误 : Heap block at X modified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28073189/

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