c - 释放在 2D 结构中分配的内存

标签 c free

您好,我有以下代码,我在 100×250 结构数组中分配内存。使用此功能后,我想释放内存,但找不到方法。

/*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 循环,或者只是 free(acard) 就足够了?

提前非常感谢您。 阿南德

最佳答案

无论您在哪里调用了 calloc 并存储了返回值,当您完成该值时都需要对该值调用 free。一般来说,只要按照与分配顺序相反的顺序释放东西,就会为您省去很多麻烦。

为此,您似乎需要像当前一样迭代并在每个 acard[i][j] 上执行 2 次释放。

你不需要在acard上调用free,但是因为这是一个堆栈变量(实际上我希望断言/崩溃尝试释放你没有用malloc/calloc/etc分配的东西..)

关于c - 释放在 2D 结构中分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14361851/

相关文章:

c - 在C中打印一个字符?为什么奇怪?

c - 每次填充 64 个整数时,我都想要一个确认打印。 ?如何检查我是否 == 64

在自己的处理程序中捕获信号

c - 测试 memcpy 函数

c - fread 未加载我的二进制文件中的内容?

java - 部署exe格式的应用程序

c - Valgrind 报告太多 malloc

如果其指针已更改类型,是否可以释放内存?

使用 free() 时 C 堆缓冲区损坏

C语言 : Error in Freeing members of struct in an a function