简体   繁体   中英

freeing a structure array allocated with double pointer

Here is basically what I'm trying to do:

free memory that was allocated in a different scope using double pointers. The following code is incomplete but fully describes what I'm trying to perform.

so here is my function to read the buffer (C pseudo code)

 char *read_buffer(char *buf, myStruct **arr, int nbElm)
 {
     buf = malloc(...);
     ...//many things done (use of the read(),close()... functions
     ...//but not referencing any of the buffer to my structure
     ...
     *arr = (myStruct *) = malloc(sizeof(myStruct) * nbElm);
     return (buf);
 }

Here is the kind of function I use between my memory allocation and my freeing attempt:

 void using_struct(myStruct *ar, int nbElm)
 {
     int i;

     i = 0;
     while (i < nbElm)
     {
         // Here I use my struct with no problems
         // I can even retrieve its datas in the main scope
         // not memory is allocated to it.
     }
 }

my main function :

int main(void)
{
    char *buf;
    myStruct *arStruct;
    int nbElm = 4;

    buf = read_buffer(buf, &arStruct, nbElm);
    using_struct(arStruct, nbElm);
    free(buf);
    buf = NULL;
    free(arStruct);
    while(1)
    {;}
    return (1);
}

The only problem is either I place my while loop before or after my free function, I can't see any memory change using top on my terminal. Is this normal?

Thanks in advance,

You always must have exactly same number of calls to free as a calls to malloc.

myStruct **arr;
*arr = malloc(sizeof(myStruct) * nbElm);

This means you need single call to free first nbElm structs:

free(arr);

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