I am currently exploring a bit in the direction of function pointers in c, and I've mocked up a little example that I feel should work, but it instead produces a segmentation fault and I am not really sure why.
Here's the code I mocked up
void *new_testarr()
{
void *testarr = malloc(4*sizeof(int));
return testarr;
}
void *test_wrap(void *(*functionpointer)(void))
{
return (*functionpointer);
}
int main(int argc, char const *argv[])
{
int *arr = (int *) test_wrap(new_testarr);
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
for (int i = 0; i < 4; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
I tested the function new_testarr() by itself and there was no problem, but as soon as I try to wrap it then a segmentation fault occurs. I also tried adding an ampersand when passing the function in test_wrap(), but the same thing happened.
Any guidance would be greatly appreciated.
return (*functionpointer);
is taking a function pointer and returning it as a void*
, which is not allowed. I think you meant to write return (*functionpointer)();
- call the function through its pointer.