C++堆损坏: Local heap variable causing issues

标签 c++ heap-memory heap-corruption

我正在使用 DirectX9 通过手动组装地面的顶点来处理一些简单的地形。

在我设置索引的代码部分,我收到了错误:

Windows 在 test.exe 中触发了断点。

这可能是由于堆损坏造成的,这表明 test.exe 或其加载的任何 DLL 中存在错误。

这是我的代码中给我带来问题的部分,我几乎 100% 确定它链接到我的索引指针,但我完成后将其删除......所以我不确定问题是什么。

int total = widthQuads * heightQuads * 6;
DWORD *indices = new DWORD[totalIdx];
for (int y = 0; y < heightQuads; y++)
{
    for (int x = 0; x < widthQuads; x++)
    { //Width of nine:
        int lowerLeft = x + y * 9;
        int lowerRight = (x + 1) + y * 9;
        int topLeft = x + (y + 1) * 9;
        int topRight = (x + 1) + (y + 1) * 9;
        //First triangle:
        indices[counter++] = topLeft;
        indices[counter++] = lowerRight;
        indices[counter++] = lowerLeft;
        //Second triangle:
        indices[counter++] = topLeft;
        indices[counter++] = topRight;
        indices[counter++] = lowerRight;
    }
}

d3dDevice->CreateIndexBuffer(sizeof(DWORD)* total, 0, D3DFMT_INDEX16, 
    D3DPOOL_MANAGED, &groundindex, 0);
void* mem = 0;
groundindex->Lock(0, 0, &mem, 0);
memcpy(mem, indices, total * sizeof (DWORD));
groundindex->Unlock();

delete[] indices;

当我删除这个 block 时,我的程序运行正常。

最佳答案

您给出的代码看起来不错 - 但有一个警告:counter 的初始值不在代码本身中。因此,要么您不从 counter = 0 开始,要么其他一些代码正在破坏您的indices 缓冲区。

这就是堆损坏的美妙之处。无法保证该错误位于代码中已删除的部分中。它可能只是隐藏了代码中其他地方存在的错误。

关于C++堆损坏: Local heap variable causing issues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586570/

相关文章:

c++ - 是否可以将模板派生的 C++ 类与 Qt 的 Q_OBJECT 混合使用?

c++ - 网 bean 10 : error: linker command failed with exit code 1 (use -v to see invocation)

c++ - 堆上数组解除分配的具体查询

C 程序仅在 Visual Studio 中的 Debug模式下,以编程方式更改 argv 在程序退出后会出现堆损坏错误。如何解决?

c++ - 从 ProPhoto RGB 到显示器配置文件的颜色转换

windows-8 - Windows 8 堆随机化

c++ - 尽管在堆上分配,但值仍被破坏

c++ - 为什么我得到 'Heap Corruption' ?

C++ 堆损坏但仅在单元测试项目中

c++ - 将 AT&T 语法转换为 Intel 语法 (ASM)