Search code examples
cmemory-managementmallocfree

Using free with double pointer to a struct


I am trying to understand how to use free function. In the following snippet, I create ctx using malloc.

void serve(ctx **some_struct_type) {
     // .. some operation
}

int main() {

  context_t* ctx = malloc(sizeof(struct context_t));
  serve(&ctx);

}

Since each malloc call must have a corresponding free call and I want to call free inside serve, should it be free((**ctx)) or free((*ctx))?

I am a little confused with the way I must invoke free.


Solution

  • You declared a pointer in main

    context_t* ctx = malloc(sizeof(struct context_t));
    

    To free the allocated memory in main you could write

    free( ctx );
    

    However you passed the pointer by reference to the function serve

    serve(&ctx);
    

    So to get the referenced object (pointer) in the function you have to dereference the pointer declared as the function parameter (I will change the function parameter to make sense to the function)

    oid serve( context_t **p ) {
    

    That is you need to write

    free( *p );
    

    where *p is the lvalue of the original object ctx.