Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading