Beren123
Beren123

Reputation: 1

How to free a struct that is inside an other struct

I have the following two structs:

typedef struct label{

    int id;
    double p,*t,q,c;

    int V[45];
    struct label *next;
    struct label *prev;
    struct path *tail;
    struct path *head;

}label;

typedef struct path{
    int i;

    struct path *Pperv;
    struct path *Pnext;
}path;

void main (){

    int i,j;
    struct label *Current,*Head,*Tail;
    struct path *test1,*path_head,*path_tail;

    Head=(struct label*)malloc(1*sizeof(struct label));
    Tail=(struct label*)malloc(1*sizeof(struct label));

    Head->next=Tail;
    Tail->prev=Head;


    for (i=0;i<250000;i++)
    {
        Current=(struct label*)malloc(1*sizeof(struct label));
        Current->t=(double*)malloc(15*sizeof(double));

        Current->head=(struct path*)malloc(1*sizeof(struct path));
        Current->tail=(struct path*)malloc(1*sizeof(struct path));
        Current->head->Pnext=Current->tail;
        Current->tail->Pperv=Current->head;

        for (j=0;j<15;j++)
        {
            test1=(struct path*)malloc(1*sizeof(struct path));

            test1->Pperv=Current->head;
            test1->Pnext=Current->head->Pnext;

            Current->head->Pnext->Pperv=test1;
            Current->head->Pnext=test1;


            test1->i=1;
            Current->t[j]=23123.4323334;

        }
        Current->next=Tail;
        Current->prev=Tail->prev;
        Tail->prev->next=Current;
        Tail->prev=Current;
        Current->p=54545.323241321;
    }
}

I just used an example of filling some of the variables in them so that I can make my question. What I am facing problem with is how to free the struct "Path" that is contained into the the first struct called name "Label".

I would me sth more than greatful if somenone could give me the code of how to correctly free both structs in C.

Upvotes: 0

Views: 196

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272752

In general, you just need to be symmetrical with the calls to malloc/calloc:

label *current = malloc(sizeof(*current));
current->head = malloc(sizeof(*current->head));

...

free(current->head);
free(current);

Upvotes: 2

Related Questions