Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Freeing a struct from a callback that is a field of the struct

Consider this code:

typedef struct Test_s Test;

typedef void (*FreePtr)(Test*);

struct Test_s{
    FreePtr freePtr;
};
    
void freeFunction(Test* t) {
    free(t);
}
void main(void) {
    Test* t = malloc(sizeof(*t));
    t->freePtr = freeFunction;
    t->freePtr(t);
}

Is it possible to free t from within freeFunction? I think it is possible, but I decided to ask as I am not quite sure.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I suspect you’re concerned that you’re freeing the pointer that you indirected through to get to the function that’s running. This isn’t a problem.

t->freePtr(t);

is equivalent to

Freeptr tempfunc = t->freePtr;
tempfunc(t);

As you can see from this rewrite, t is not still in use while the function is running.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading