c - Freeing structure of structures that were allocated by malloc causes error? -


so i'm trying make game using c , have following types :

typedef struct{     float x;     float y; } vector;  typedef struct{     vector *vec;     void (*update)(); } velocity;  typedef struct{     vector *vec;     velocity *vel;     void (*move)(); } hero; 

and here following code giving me error:

hero *h; // allocate memory hero  h = malloc(sizeof(hero*)); // allocate memory velocity h->vel = malloc(sizeof(velocity*));  // initialize vectors h->vec = malloc(sizeof(vector*)); h->vel->vec = malloc(sizeof(vector*));  free(h->vec); // free hero vector free(h->vel->vec); // free velocity vector free(h->vel); // free velocity free(h); // free hero 

for reason, free(h->vel) gives me error when trying free velocity. why happen? in advance!!

when this:

h = malloc(sizeof(hero*)); 

you're allocating space pointer hero, not instance of hero.

as result, you're not allocating enough memory structs, , writing fields of struct writes past end of allocated memory. invokes undefined behavior, in particular case manifests crash when calling free.

removed * operator sizeof expressions allocate enough space instance of structs:

hero *h; // allocate memory hero  h = malloc(sizeof(hero)); // allocate memory velocity h->vel = malloc(sizeof(velocity));  // initialize vectors h->vec = malloc(sizeof(vector)); h->vel->vec = malloc(sizeof(vector)); 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -