给free()在C malloc分配二维数组最佳方式 [英] Optimal way to free() a malloc'ed 2D array in C

查看:494
本文介绍了给free()在C malloc分配二维数组最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假如我有一个与像这样创造了一个2维数组,

Supposing I have a 2 dimensional array which was created with something like this,

char **foo = (char **) malloc(height * sizeof(char *));
for(i = 0; i <= height; i++) 
    foo[i] = (char *) malloc (width * sizeof(char *));

首先,这甚至创建一个这样的数组的正确方法?美中不足的是在这里,高度和宽度的东西是在运行时设置的。

First of all, Is this even the right way to create an array like this?. The catch here is, 'height' and 'width' is something that is set during runtime.

这似乎是工作,但它是释放这个二维数组的最佳策略。
免费(funge)听起来错误的。一些其他职位在这里发生,我想我会有免费的每个的行逐一?

This seems to work, but which is the best strategy to free this 2d array. free(funge) sounds wrong. Going by some other posts in here, I guess I will have free each row one by one?

我也尝试这样的事情,

for (height = 0; height < ip_ptr->funge_height; height++) {
    free(funge[height]);
} 
free(funge)

本,但给了我一个双重释放指针异常。这是否意味着,我没有管理这块内存?我是IM pression,对于每一个malloc分配内存,我们应该叫免费的()。

This, however gives me a double free pointer exception. Does this mean, I don't have to manage this piece of memory?. I was of the impression that, for every malloc'ed memory we should call free().

推荐答案

由于所有的行的大小相同,你可以分配它一举,以的malloc(高*宽*的sizeof(字符*))(它不管你是创建字符的二维数组或<$ C $的二维数组不是完全清楚C>的char * )。您可以用乘法来计算相应的指数(即 foo的[I] [J] 变成富+ I *高+ J ),

Since all the 'rows' are the same size, you can just allocate it in one swoop, with malloc(height * width * sizeof (char *)) (it's not entirely clear whether you're creating a 2d array of char or a 2d array of char *). You can use multiplication to calculate the appropriate index (i.e. foo[i][j] becomes foo + i * height + j),

免费() ING将同样采取单一的电话。

free()ing it will similarly, take a single call.

这篇关于给free()在C malloc分配二维数组最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆