Reputation: 2643
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!
Upvotes: 0
Views: 479
Reputation: 121759
Maybe you might also want to pass the parameter "v"?
t->f = blah; // BAD
t->f = blah (SOMETHING); // Better...
Upvotes: 0
Reputation: 7115
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.
Upvotes: 7