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

How to free a struct with a function pointer member?

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 :

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

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

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