如何阻止此内存泄漏?

时间:2015-03-27 15:28:31

标签: c++ memory-leaks

我已将程序内存泄漏缩小到其中一个动态创建的内容。泄漏非常小并且没有问题,但最好修复,这是代码:

//allocate row memory:
dynamicNodeArray = new int *[r];
//allocate column memory:
for(int i = 0; i < r; i++)
{
    dynamicNodeArray[i] = new int[c];
}

//...

//allocate memory for nodes (array of structs):
node* nodes = new node[r*c];

//...

//clean up:
for(int i = 0; i < r; i++)
{
    delete dynamicNodeArray[i];
}

delete dynamicNodeArray;
free(nodes);
delete nodes;

1 个答案:

答案 0 :(得分:5)

当您使用delete dynamicNodeArray;分配时,

delete [] dynamicNodeArray;应为new[]

也永远不要在free()new()分配的内容上致电new[]