在C中释放()malloc的二维数组的最佳方法

sud*_*rsh 1 c memory arrays free pointers

假设我有一个用这样的东西创建的二维数组,

char **foo = (char **) malloc(height * sizeof(char *));
for(i = 0; i <= height; i++) 
    foo[i] = (char *) malloc (width * sizeof(char *));
Run Code Online (Sandbox Code Playgroud)

首先,这甚至是创建像这样的数组的正确方法吗?这里的问题是,'height'和'width'是在运行时设置的东西.

这似乎有效,但这是释放这个2D阵列的最佳策略.免费(funge)听起来不对.通过这里的其他帖子,我想我会逐一释放每一行?

我确实试过这样的事,

for (height = 0; height < ip_ptr->funge_height; height++) {
    free(funge[height]);
} 
free(funge)
Run Code Online (Sandbox Code Playgroud)

然而,这给了我一个双重自由指针异常.这是不是意味着,我不需要管理这段记忆?我的印象是,对于每个malloc的内存,我们应该调用free().

Mic*_*ngh 8

由于所有'行'都是相同的大小,你可以一次性分配它malloc(height * width * sizeof (char *))(不完全清楚你是创建一个二维数组char还是一个二维数组char *).您可以使用乘法来计算适当的索引(即foo[i][j]变为foo + i * height + j),

free()同样,只需一个电话.


Pon*_*ing 8

在用于分配的for循环中,您使用的是i <= height;代替i < height;.因此,您正在写入无效的内存位置,并且代码的行为变得不可预测.

  • 那么,如何回答一个题为"最佳方式......"的问题.你的意思是"最佳"的"崩溃"吗? (2认同)

for*_*ran 7

第二个分配应该是:

foo[i] = (char *) malloc (width * sizeof(char));
Run Code Online (Sandbox Code Playgroud)

你也在height+1分配时循环.

除此之外,这两个片段对我来说似乎是正确的,所以错误应该在其他地方.

如果数组只被分配为一大块内存,那么你只需要释放一次.

char **foo = (char **) malloc(height * sizeof(char *));
*foo = malloc(height * width * sizeof(char))
for (int i = 1; i < height; i++) {
  foo[i] = *foo + i*width;
}
//and you just do 2 frees
free(*foo);
free(foo);
Run Code Online (Sandbox Code Playgroud)