【问题标题】:HeapFree Has triggered a breakpointHeapFree 已触发断点
【发布时间】: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-trait std::is_pod&lt;STestStruct&gt;::value 来检查它的 POD-ness。使用 new 而不是 malloc

标签: c++ free


【解决方案1】:

当您将n 添加到指针时,指针不会(必然)增加n 字节。它们以sizeof(*p) * n 字节递增。

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

【讨论】:

  • 谢谢!我没有意识到我犯了这么愚蠢的错误。
【解决方案2】:

你想要的

STestStruct* testStruct2 = testStruct + 1; 

因为指针总是以其基类型的大小为单位递增。

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多