gpt4 book ai didi

c - 在 C 中取消引用 struct void 指针

转载 作者:行者123 更新时间:2023-11-30 17:48:10 27 4
gpt4 key购买 nike

我有一个 MyLib.h,其中有

typedef void *MyThread;

和一个 MyLib.c,其中包含:

typedef struct
{
ucontext_t *context;
int tid;
}_MyThread;

有一个测试函数可以创建线程并发出连接:

void f0(void * dummy)
{
MyThread t1;
printf("f0 start\n");
t1 = MyThreadCreate(f1, NULL);
_MyThread *t = (_MyThread*)t1;
printf("passed value=%d\n",t->tid);

printf("f0 join on t1\n");
MyThreadJoin(t1);
....
}

MyLib.c中的MyThreadCreate和MyThreadJoin如下:

MyThread MyThreadCreate(void(*start_funct)(void *), void *args)
{
_MyThread child_thread;
...
//setting the child thread's tid
child_thread.tid = ++active_threads;
... MyThread ret = (MyThread)&child_thread;
return ret;
}

int MyThreadJoin(MyThread thread)
{
_MyThread *arg_thread;
arg_thread = (_MyThread*)thread;
int id = arg_thread->tid;
....
}

我的问题是,当我运行上面的代码时,我得到:

passed value=2
f0 join on t1
arg_thread->tid = 13

传递的值=“2”是正确的,但是库函数中出现的值“13”是错误的。为什么传递的值以相同的方式取消引用,与调用函数和被调用函数不同?

最佳答案

你能添加代码来打印出arg_thread和t的内存地址吗?我有一种感觉,发生的事情是你的指针被强制转换切成两半。 MyThreadJoin 在 MyLib.h 中是否正确前向声明?您是否将代码编译为 64 位?

[编辑]我刚刚看到你在创建 t 时的评论。看起来您是在堆栈上分配它(而不是堆)。当您向上访问堆栈帧时,它的内存尚未被覆盖。当您将新函数压入堆栈时,它会覆盖 t 上的内存。简单的解决方案是在构造函数中 malloc 结构。

关于c - 在 C 中取消引用 struct void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18688280/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com