C 释放2D结构中分配的内存
嗨,我有下面的代码,我在100x250结构数组中分配内存。使用后,我想释放内存,但我无法找到一种方法C 释放2D结构中分配的内存,c,free,C,Free,嗨,我有下面的代码,我在100x250结构数组中分配内存。使用后,我想释放内存,但我无法找到一种方法 /*trial programe for storing sample data for each beam of each ping*/ #include <stdio.h> #include <math.h> typedef struct{ // in this structure we will define the pointers. so just data
/*trial programe for storing sample data for each beam of each ping*/
#include <stdio.h>
#include <math.h>
typedef struct{ // in this structure we will define the pointers. so just data type and variable.
int count;
float *samples;
float *deTVG_BS;
} card;
main()
{
//float a,*p;
int i,j,k,l,m,variable;
l=100;
m=250;
variable=10;
card acard[l][m];
//printf("size of acard before memory allocation is %d\n",sizeof(acard));
/* now we will alocote memory for all the pointers we have defined in structure.
* The memory size can be different for each pointer.
* In our case memory size will depends on number of samples for each beam.
* * */
for(i=0;i<l;i++) // i is number of profiles
{
for (j=0;j<m;j++) // j is number of beam
{
acard[i][j].count=variable; //from 1 to 400;
acard[i][j].samples=(float*)calloc(acard[i][j].count,sizeof(float));
acard[i][j].deTVG_BS=(float*)calloc(acard[i][j].count,sizeof(float));
for(k=0;k<acard[i][j].count;k++)
{
acard[i][j].samples[k]=k*1.0;// in reality will be different values
acard[i][j].deTVG_BS[k]=k*100.0; // in reality will be different values
}
}
printf("allocated memeory for profile %d\n",i);
}
for(i=0;i<l;i++) // i is number of profiles
{
for (j=0;j<m;j++)
{
void free(acard[i][j].samples);
void free(acard[i][j].deTVG_BS);
}
}
void free(acard);
}
我不确定是应该运行最后一个for循环,还是仅仅使用freeacard就足够了
事先非常感谢你。
Anand无论您在哪里调用calloc并存储返回值,都需要在使用完该值后调用free。一般来说,只需按分配的相反顺序释放物品,就可以省去很多麻烦 为此,看起来您需要像当前一样对每个acard[i][j]进行迭代和2次释放 您不需要在acard上调用free,但是因为这是一个堆栈变量,实际上我希望在尝试释放您没有使用malloc/calloc/etc分配的内容时断言/崩溃