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 wrap a function that returns void * in c

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.

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

Any guidance would be greatly appreciated.

>Solution :

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.

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