HeapFree触发了一个断点

HeapFree Has triggered a breakpoint

本文关键字:一个 断点 HeapFree      更新时间:2023-10-16

我一直在摆弄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之后,我没有修改指针中的任何内容。知道是怎么回事吗?

指针在添加n时,不(不一定)增加n字节。它们以sizeof(*p) * n字节递增。

因此,您将testStruct2增加sizeof(STestStruct) * sizeof(STestStruct)字节,太多了。只需要添加1,即"移动到下一个STestStruct对象的块。

你想

STestStruct* testStruct2 = testStruct + 1;