I know void * and function pointers cannot be safely converted either way.
My question is the below code.
#include <stdio.h>
#include <stdlib.h>
void f(void *);
void g(void) {
printf("hello world\n");
}
int main(void) {
void (*p)(void) = g;
void (**pp)(void) = malloc(sizeof(void (*)(void)));
pp = &p;
f(pp);
free(pp); //segfault
return EXIT_SUCCESS;
}
void f(void *p) {
(*(void (**)(void))p)();
}
It compiles well in gcc with -Wall -Wextra -pedantic -std=c99, but fails in runtime when the program calls free. What is wrong in this case? Is a pointer to function pointer not a data pointer?
Afterthought:
The correct code is this,
int main(void) {
void (*p)(void) = g;
f(&p);
return EXIT_SUCCESS;
}
I have no idea why I got confused :/
ppalready rewrite by&p.free(pp)is UB.malloc()and understand deeply what it does and what it is for.