Home > other >  freeing container does it free the child both allocated on heap. I do not think that
freeing container does it free the child both allocated on heap. I do not think that

Time:11-20

I have two structs

struct request
{
    char *request;
    char *rand;
    int status;

}
struct container 
{
    int new_socket;
    struct request **request;
}

let say I create a pointer of request

 struct request *requests = malloc(sizeof(struct request));

and I create pointer pointing to space in heap of container like

 struct container *con=malloc(sizeof(struct container))

and I do

 con->new_socket = 1;
 con->request= &request

and if I free like free(con), And so I really don't thing my requests pointer get freed. I think its present and I can access elements of it like *(requests 0)->status and this will be ok. Is this correct understanding if I am struct request requests accessible somewhere else in my program

CodePudding user response:

And so I really don't thing my requests pointer get freed.

That's correct. free() only frees a single malloc(). If you call malloc() twice, and free() once, then only one of the two allocations is freed.

If you run this code:

struct request *requests = malloc(sizeof(struct request));
struct container *con=malloc(sizeof(struct container))
con->new_socket = 1;
con->request= &request;
free(con);

then the heap memory pointed to by the requests pointer will not be freed.

  •  Tags:  
  • c
  • Related