释放内存时出现严重错误



我有一个结构"索引",其中包含索引的缓冲区(DirectX,但我认为这无关紧要):

struct Indices {
    CComPtr<ID3D11Buffer> buffer;
    UINT indexCount;
};

以及使用类索引的对象初始化数组的方法:

mIndices = new Indices*[layers];
for( int i = 0; i < layers; ++i )
    mIndices[i] = new Indices[corrections];
//... initializing buffers

和释放内存的方法:

for( int i = 0; i < layers; ++i )
    delete mIndices[i];                // here I am getting critical error
delete mIndices;

但是当我尝试释放内存时,我收到"检测到严重错误 c0000374"(在上面的代码中指出)。

你能帮帮我吗?我希望发布的代码足以解决我的问题。

谢谢

当你使用新的 T[n] 创建数组时,你还必须使用 delete[] 来释放内存:

for( int i = 0; i < layers; ++i )
    delete[] mIndices[i];
delete[] mIndices;

手动内存管理是一个麻烦,很容易导致崩溃和内存泄漏。你有没有考虑过std::vector?它可以用作动态数组的直接替代品:

// create and initialize the arrays
std::vector< std::vector<Indices> > indices(layers, std::vector<Indices>(corrections));
// will be automatically freed when lifetime ends

由于您正在分配数组,因此您应该解除分配数组。使用 delete[] 而不是 delete

最新更新