开发者

how do I release a struct from memory and arrays within them

I want to know how I can release a struct properly from memory and compl开发者_JAVA百科etely wipe it. I also need to wipe arrays or values within this struct. I tried just overwriting the struct with new data everytime the data changed but I observed a steady rise in memory use until I get a memory warning so I think my safest bet is to completely wipe the data first and then write to it again.

    typedef struct {


        SInt16  *array1;     
        SInt16  *array2;    

    } myStruct, *myStructPtr;


 myStructArray        myStruct[16];

    for(int i=0;i<16;i++)

    {
        myStruct[i].array1 =
        (AudioUnitSampleType *) calloc (asize, sizeof (SInt16));

        myStruct[i].array2 =
        (AudioUnitSampleType *) calloc (asize, sizeof (SInt16));

    }

   free(myStructArray) // throws SIGBART error


You didn't malloc or calloc myStructArray so you shouldn't free it. Loop over the elements and free myStruct[i].array1 and array2

for(int i=0;i<16;i++)
    {
        free(myStruct[i].array1);
        free(myStruct[i].array2);
    }

The general rule is simple - free what you malloc/calloc/realloc/strdup/other allocs, nothing more or less. Note that alloca is an exemption - it allocates on stack, so you should never free what you got from it.


myStructArray myStruct[16];

myStruct is an array of objects created on stack. You can not call free on it. free needs to be called on resources acquired from free store ( using malloc, realloc etc., ). Instead you need call free on struct members array1, array2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜