Amanda
Amanda

Reputation: 2143

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.

Upvotes: 1

Views: 111

Answers (3)

WENDYN
WENDYN

Reputation: 740

malloc function is used for allocating certain amount of memory during the execution of a program. It sends request to the OS and if it is possible the OS will reserve the requested amount of memory from the heap. (The function returns address of allocated space)

+-------+------------------+------+----------------------+
| stack | -> free space <- | heap | data & code segments |
+-------+------------------+------+----------------------+

free works in the other way, it takes the address (reference) that points to some memory block and deallocates it.

If you want it to be deallocated in main, you would do it like this:

int main() {

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

}

but since you are converting it to double pointer (pointer to pointer) you need to dereference it back to that address you allocated:

int main() {

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

  ctx **some_struct_type = &ctx;

  free(*some_struct_type);

}

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

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.

Upvotes: 1

dbush
dbush

Reputation: 223699

In main, the value of ctx is address of a block of allocated memory. It is this value that gets passed to free.

If you pass the address of ctx to a function, then you need to dereference that pointer to get the pointer value that you got from malloc.

So assuming the function is declared as:

void serve(struct context_t **ctx) {

You want free(*ctx) inside of this function.

Upvotes: 0

Related Questions