分配并释放一系列杠杆2指针? [英] Allocate and free an array of lever 2 pointer?
本文介绍了分配并释放一系列杠杆2指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个杠杆2指针阵列** f [5] - > f [5] [6] [7],我想将它们分配给堆内存然后释放它们,怎么做?谢谢。
我这样做会导致内存泄漏:
- 分配它们:
I have an array of lever 2 pointer **f[5] -> f[5][6][7], I want to allocate them on Heap memory and then free them, how to do this? Thanks.
I get memory leak when I do it:
- Allocate them:
for (int i=0;i<5;i++)
{
f[i]= new int*[6];
for (int j=0;j<6;j++)
f[i][j]= new int[7];
}
并将它们释放如下:
And free them as follows:
for (i=0;i<6;i++)
delete[] f[i];
我的完整代码如下:
My full code is as follows:
// a.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int i, j;
int **f[5]; // f[5][6][7]
for (i=0;i<5;i++)
{
f[i]= new int*[6];
for (j=0;j<6;j++)
f[i][j]= new int[7];
}
for (i=0;i<5;i++)
for (j=0;j<6;j++)
for (int k=0;k<7;k++)
f[i][j][k]=i*j*k;
for (i=0;i<5;i++)
{
for (j=0;j<6;j++)
delete[] f[i][j];
delete[] f[i];
}
return 0;
}
我收到两个警告(我的项目名称是a):
And I get two warnings (the name of my project is "a"):
Warning 1 warning C6211: Leaking memory 'f[0]' due to an exception. Consider using a local catch block to clean up memory: Lines: 9, 10, 12, 13, 14 c:\users\peter\desktop\a\a\a.cpp 12 a
Warning 2 warning C6211: Leaking memory 'f[0][8]' due to an exception. Consider using a local catch block to clean up memory: Lines: 9, 10, 12, 13, 14, 13, 14, 13, 14, 13, 10, 12 c:\users\peter\desktop\a\a\a.cpp 14 a
我不明白他们。你能帮我检查一下吗?谢谢。
I dont understand them. Can you help me check it. Thanks.
推荐答案
首先,你正在使用立即常量 5,6和7.即使你没有错误,它也是'这是绝对不可接受的,因为它使你的代码完全不受支持。您只需要两个常量:内部数组维度和数组数组的维度;并且你必须明确地声明它们。
现在,没有显示解决方案(请自己做;只有在这种情况下你才能学会做某事),我''会告诉你明显的错误:
你在两个嵌套循环中进行分配。在外循环中,你调用运算符new
5次,在内循环中,你在每次迭代中执行6次,所以你调用运算符新的
(6 + 1)* 5 =共35次。
当你进行释放时,你打电话给delete []
在一个循环中,6次。难怪你有内存泄漏。
现在,想一想并解决它。如果很难想象,在纸上绘制分配的内存区域并编写代码。这真的很容易。
祝你好运,
-SA
First of all, you are using immediate constants 5, 6 and 7. Even if you had no bugs, it''s absolutely unacceptable, as it makes your code totally unsupportable. You need only two constants: the inner array dimension, and the dimension of the array of arrays; and you have to declare them explicitly.
Now, without showing a solution (please do it by yourself; only in this case you can learn to do something), I''ll show you the apparent bug:
You do allocation in two nested loops. In outer loop, you call the operatornew
5 times, in inner loop, you do it 6 times in each iteration, so you call call the operatornew
(6 + 1) * 5 = 35 times altogether.
When you do deallocation, you calldelete[]
in a single loop, 6 times. No wonder you have a memory leak.
Now, think just a bit and fix it. If it''s hard to imagine, draw the allocated memory area on paper and write the code. This is really easy.
Good luck,
—SA
这篇关于分配并释放一系列杠杆2指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文