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.
>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.