简体   繁体   中英

How to use alloca to allocate C function pointers?

C is a mystery all the time!

I am implementing a work-crew thread execution model in which I am trying to use alloca as a faster memory allocation option. I have a strange segmentation fault while trying to execute code via function pointers stored on the stack using alloca.

Here's a tooth-pick code which results in a similar segmentation fault:

#include <stdlib.h>
#include <stdio.h>

typedef void* (*foo)(void*);

typedef struct task
{
    foo f;
} task;

void *blah(void* v)
{
    printf("addr:%p\n", &v);
    return v;
}

int main()
{
    void *queue[10]; 

    task *t = (task*) alloca (sizeof(task));
    // No null check, excuse me!
    t->f = blah;

    queue[0] = (void*)t;
    char string[10] = "Bingo!";
    char *c = &string[0];

    task *tnew = (task*)&queue[0];
    tnew->f((void*)c);

    return 0; 
}

When I execute the above code I get a segmentation fault at the tnew->f() line. GDB backtrace did not help me much.

Kindly explain the error in the above code.. I am using alloca for the first time.

Thank you very much!

Change this line:

task* tnew = (task*)&queue[0];

to

task* tnew = (task*)queue[0];

Because queue[0] is already a pointer; you don't need to take the address of it. You have the same issue inside blah . Your printf won't crash, but it will print out the address of the pointer, not the value of the pointer, which probably isn't what you want.

Maybe you might also want to pass the parameter "v"?

t->f = blah; // BAD

t->f = blah (SOMETHING); // Better...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM