for example have following struct:
struct student{ char *studentname; int studentage; struct student *next; };
i have many instances of student struct (for many different students) in linked list. each variable within struct strdup'd (except int's).
now after doing processing program set out do, want add function free struct instances , free variables have been strdup'd. there way can in quick manner?
it's unclear mean "in quick manner" or "all @ once". best guess looking standard library function in 1 call automagically free memory want freed. there indeed such function: exit()
. unfortunately, other effects unlikely compatible purposes.
otherwise, there no standard library function achieves you're after. standard library functions in general , memory management functions in particular don't understand contents of struct
s. not, instance, have ability recognize of struct
members pointers might need referrents deallocated, too. if detect that, not safe them perform deallocation, because cannot know whether there other pointers same dynamic memory.
the usual approach sort of problem revolves around writing own function free instances of struct
, along members thereof need deallocation. example:
void free_student(struct student *s) { free(s->studentname); free(s); }
that has distinct advantage if ever modify struct
can change deallocation function appropriate, instead of changing ad-hoc deallocation code in multiple places.
you might make such function double duty free next student in list, recursively, cleaner have separate function purpose (that uses first):
void free_student_list(struct student *head) { while (head) { struct student *next = head->next; free_student(head); head = next; } }
such approach predicated on certainty members can , should freed, must take care members intend free indeed point allocated memory, not alias each other, , there no presumed-valid pointers same memory elsewhere in program.
Comments
Post a Comment