1

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);
1
  • 2
    You don't have to, you use free with ponters pointing to a (m/re/c)alloced area. Here number is not a pointer. Commented Nov 7, 2021 at 6:40

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

The lifetime of the structure whose memory was reserved with malloc is allocated, not automatic, and so too is the lifetime of any member within it.
Indeed. However, I was sitting of the char array within the struct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.