简体   繁体   中英

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 completely 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM