How to free a struct with a function pointer member?

Advertisements

I am allocating a struct with a function pointer. Obviously, I have to free the struct at the program end. However, freeing a function pointer leads to undefined behavior. How should I do it? I tried to create a pointer to this pointer to a function point but it does not work, right? Attached a minimal example.

#include <stdlib.h>
#include <stdio.h>

int le_double(void *a, void *b){return *(double *)a < *(double *)b;}
 
typedef struct example
{
   double* data;  
   int (*le_fun)(void *, void *);
} Example;

Example* ExampleNew(int nItems)
{
   int size = sizeof(Example) + nItems * sizeof(double);
   Example* e =  malloc(size);
   e->data = (double *) (e + 1);
   e->le_fun = le_double;
   return e;
}
 
void test(int nItems)
{
   Example* e = ExampleNew(nItems);
   free(e);
}

int main()
{
   int nItems = 5;
   test(nItems);
}

>Solution :

You allocated one block of memory, and you freed that block of memory. That’s all there is to do.

We say we free a pointer, but that’s just a shorthand. We actually free that to which the pointer points. e->le_fun points to a function. You never allocated the memory used by the function, so you are not responsible for freeing it. It would be incorrect to call free( e->le_fun ).

Leave a ReplyCancel reply