carlosdafield
carlosdafield

Reputation: 1537

How to free char array in struct

I see that you can free char * pointers within struct but how do you free char[N] inside a struct

typedef struct Edge
{
    char number[13];
    int numOfCalls;
    struct Edge *next;
} Edge;

When I do this i get an error

Edge *edge = malloc(sizeof(Edge));
edge->next = NULL;
strcpy(edge->number,numberOne);  // numberOne is also a char[13];
free(edge->number);
free(edge);

Upvotes: 1

Views: 773

Answers (2)

Guseul Heo
Guseul Heo

Reputation: 28

If you use char array (char number[13]) in struct, you don't have to malloc or free the array. Once you do malloc for struct Edge, there is also space for number in memory.

In summary, if you use char pointer as a member of struct Edge, you need to malloc or free memory space for char pointer, but you don't have to do that in your case. Therefore, delete free(edge->number) line.

Upvotes: 1

Chris
Chris

Reputation: 36536

The lifespan of number in the struct Edge is automatic. Even if you dynamically allocate an Edge struct, when you free the struct, you'll free the memory for the char array.

Upvotes: 0

Related Questions