【发布时间】:2014-06-15 22:25:56
【问题描述】:
我一直在搞乱 malloc 和 free,我遇到了一个问题,当我调用 free visual studio 时说我的程序触发了断点。这是我收到的错误:
HEAP: Free Heap block 5371d0 在被释放后修改为 537230
这是我的代码:
#include <malloc.h>
struct STestStruct
{
STestStruct(int _a, int _b, int _c)
: a(_a), b(_b), c(_c)
{
}
int a;
int b;
int c;
};
int main(int argc, char** argv)
{
void* myMem = malloc(sizeof(STestStruct) * 2);
STestStruct* testStruct = (STestStruct*)myMem;
(*testStruct) = STestStruct(1, 2, 3);
// If I comment this and the next line out, everything is fine
STestStruct* testStruct2 = testStruct + sizeof(STestStruct);
(*testStruct2) = STestStruct(1, 2, 3);
free(myMem);
return 0;
}
让我感到困惑的是,在我调用 free 之后,我并没有修改指针中的任何内容。关于发生了什么的任何想法?
【问题讨论】:
-
再看一下 + 运算符对指针的作用。
-
有点相关。我认为它在 c++ 中的工作方式完全相同,您可以在标准中找到类似的段落。 stackoverflow.com/questions/24116884/…
-
注意:将
malloc与非 POD 类一起使用会导致未定义的行为。 (你可以使用 type-traitstd::is_pod<STestStruct>::value来检查它的 POD-ness。使用new而不是malloc。