Skip to content

Instantly share code, notes, and snippets.

@LizzyFleckenstein03
Last active January 15, 2023 15:33
Show Gist options
  • Save LizzyFleckenstein03/313575263c902a6cbe3dc538055aa796 to your computer and use it in GitHub Desktop.
Save LizzyFleckenstein03/313575263c902a6cbe3dc538055aa796 to your computer and use it in GitHub Desktop.
/*
If -Wpedantic is enabled, casts between function pointers and void* are forbidden.
("ISO C forbids conversion of function pointer to object pointer type")
However, a function pointer can be wrapped in a struct, a pointer to which can in turn be casted to void*.
This program demonstrates how this trick can be abused to cause undefined behavior.
Build: cc -Wall -Wextra -Wpedantic -Werror callback.c -o callback
Run: ./callback
License: CC BY-SA 4.0
*/
#include <stdio.h>
struct func_pointer_1 {
void (*ptr)(char *);
};
struct func_pointer_2 {
void (*ptr)(void *, void *);
};
void my_func(char *str)
{
printf("%s", str);
}
void call_func(void *fn, void *arg1, void *arg2)
{
// undefined behavior (but works on my machine)
((struct func_pointer_2 *) fn)->ptr(arg1, arg2);
}
int main()
{
call_func(&(struct func_pointer_1) { &my_func }, "hello\n", NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment