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);
CodePudding user response:
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.
CodePudding user response:
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.