if have several linked structures in c like:
struct structa { int a; int b; struct structa *next; } struct structb { char a; int b; struct structb *next; } and dynamically allocate memory this:
struct structa *mystructa = (struct structa*) malloc(sizeof(struct structa)); mystructa->next = (struct structa*) malloc(sizeof(struct structa)); struct structb *mystructb = (struct structb*) malloc(sizeof(struct structb)); mystructb->next = (struct structb*) malloc(sizeof(struct structb)); do have free each struct type this:
struct structa *p, *pnext; (p = mystructa; p != null; p = pnext) { pnext = p->next; free(p); } struct structb *p, *pnext; (p = mystructb; p != null; p = pnext) { pnext = p->next; free(p); } or there generic solution? assume there no other solution because free() procedure must know how many bytes have freed. maybe i'm wrong , can teach me better.
the standard way make "list part" first element of structure, , let each derived struct share same prefix. since first element guaranteed placed @ offset 0 wil work. example snippet:
#include <stdlib.h> #include <string.h> struct list { struct list *next; }; struct structa { struct list list; int a; int b; }; struct structb { struct list list; char a; int b; }; void *create_any(size_t size) { struct list *this; = malloc (size); if (!this) return this; memset(this, 0, size); this->next = null; return this; } void free_all_any(struct list **lp) { struct list *tmp; while ((tmp = *lp)) { *lp = tmp->next; free(tmp); } } #define create_a() create_any(sizeof(struct structa)) #define create_b() create_any(sizeof(struct structb)) #define free_a(pp) free_any((struct list **) pp) #define free_b(pp) free_any((struct list **) pp) int main(void) { struct structa *ap; struct structb *bp; ap = create_a (); bp = create_b (); // code here ... free_a( &ap); free_b( &bp); return 0; } this more or less method used in linux kernel, lot more preprocessor magic used there. (and there no malloc there, obviously)
Comments
Post a Comment