Error : Heap block at X modified
Error : Heap block at X modified
我试图对结构使用析构函数。但是,编译器报错Heap block at 006651F8 modified at 00665229 past requested size of 29 gift1.exe has triggered a breakpoint.
#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);
,也会出现相同的错误。 Heap block at 00EA68D8 modified at 00EA6909 past requested size of 29 gift1.exe has triggered a breakpoint.
_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()
并防止复制或为 [=19 实施复制=]).
如果您检查 the documentation for _strdup
(aka strdup
),您会看到它在内部使用 malloc
来分配字符串,因此必须通过调用 free
而不是 [=14] 来释放内存=].
我试图对结构使用析构函数。但是,编译器报错Heap block at 006651F8 modified at 00665229 past requested size of 29 gift1.exe has triggered a breakpoint.
#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);
,也会出现相同的错误。 Heap block at 00EA68D8 modified at 00EA6909 past requested size of 29 gift1.exe has triggered a breakpoint.
_strdup
在内部使用 malloc()
:
The
_strdup
function callsmalloc
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()
并防止复制或为 [=19 实施复制=]).
如果您检查 the documentation for _strdup
(aka strdup
),您会看到它在内部使用 malloc
来分配字符串,因此必须通过调用 free
而不是 [=14] 来释放内存=].