-2

こんにちは、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) だけで十分なのかわかりません。

よろしくお願いします。アナンド

4

1 に答える 1

0

callocを呼び出して戻り値を格納した場合は、終了時にその値をfreeで呼び出す必要があります。一般的に、割り当てたのとは逆の順序で物を解放するだけで、多くの頭痛の種を減らすことができます。

このため、現在のように、各acard [i] [j]を繰り返して、2回の解放を行う必要があるようです。

ただし、これはスタック変数であるため、カードでfreeを呼び出す必要はありません(実際には、malloc / callocなどで割り当てていないものを解放しようとすると、アサート/クラッシュすると予想されます)。

于 2013-01-16T15:31:13.033 に答える