如何使用alloca分配C函数指针?
C一直是个谜!
我正在实现一个工作人员线程执行模型,其中我尝试使用 alloca 作为更快的内存分配选项。我在尝试使用 alloca 通过存储在堆栈上的函数指针执行代码时遇到了奇怪的分段错误。
这是一个牙签代码,它会导致类似的分段错误:
#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;
}
当我执行上述代码时,我在 tnew->f() 行处收到分段错误。 GDB 回溯对我没有多大帮助。
请解释上面代码中的错误。我是第一次使用 alloca。
非常感谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将此行更改为:
因为
queue[0]
已经是一个指针;你不需要获取它的地址。您在blah
中也遇到了同样的问题。你的 printf 不会崩溃,但它会打印出指针的地址,而不是指针的值,这可能不是你想要的。Change this line:
to
Because
queue[0]
is already a pointer; you don't need to take the address of it. You have the same issue insideblah
. Yourprintf
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.也许您还想传递参数“v”?
Maybe you might also want to pass the parameter "v"?