【发布时间】:2016-09-20 21:35:00
【问题描述】:
我想知道在 2D 数组创建失败期间清理已分配的内存的最佳方法是什么。
int** a = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i != rows; ++i)
a[i] = (int*)malloc(columns * sizeof(int));
for (int i = 0; i != rows; ++i)
free(a[i]);
free(a);
上面的示例代码应该像魅力一样工作。但是malloc 可以返回null,而当它返回时,上面的代码将无法处理该问题。我们如何保护这种情况?
假设(int*)malloc(columns * sizeof(int)) 为i = 3 返回了null。我们已经为int** a 和a[0]、a[1] 和a[2] 分配了空间。
这是我目前的方法。丑陋,不确定是否正确。这就是我向您寻求帮助的原因。
int rows;
int columns;
scanf("%d", &rows);
scanf("%d", &columns);
int** a = (int**)malloc(rows * sizeof(int*));
if (!a)
{
printf("Cannot allocate enough space."); // nothing to clean up here
return 1; // to make example easier
}
int i;
bool arrayCreated = true;
for (i = 0; i != rows; ++i)
{
int* tmp = (int*)malloc(columns * sizeof(int));
if (!tmp) // malloc returned null
{
arrayCreated = false; // let's mark that we need to do some cleanup
break;
}
a[i] = tmp;
}
if (!arrayCreated) // creation failed, clean up is needed
{
for (int j = 0; j <= i; ++j)
free(a[j]);
}
else
{
for (int i = 0; i != rows; ++i)
free(a[i]);
}
free(a);
【问题讨论】:
-
@πάνταῥεῖ 很高兴看到一个完整的例子。你介意分享吗?
-
很多问题,最好一次发布一种语言。
-
@ArchbishopOfBanterbury 我喜欢容器和智能指针,我一直在使用它们。我只是想知道过去是怎么做到的。
-
@dptd 不要混用
new、malloc和free。这是一个强有力的规则。 -
@dptd 还请详细说明您的问题,为什么您认为这些 cmets 和答案实际上是无用?这些是处理内存分配的惯用方法。如果您想要不同的东西,请选择另一种编程语言,
标签: c memory-management memory-leaks null malloc