JSmith
JSmith

Reputation: 4808

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,

Upvotes: 1

Views: 361

Answers (1)

4pie0
4pie0

Reputation: 29724

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);

Upvotes: 2

Related Questions