简体   繁体   English

在C中解引用struct void指针

[英]Dereferencing struct void pointer in C

I have a MyLib.h which has 我有一个MyLib.h

typedef void *MyThread;

and a MyLib.c which has: 和一个MyLib.c,其中包含:

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

there is a test function that creates a thread and issues a join as: 有一个测试函数可以创建线程并发出联接,如下所示:

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);
....
}

MyThreadCreate and MyThreadJoin in MyLib.c are as follows: 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;
....
}

My problem is, when I run the above, I get: 我的问题是,当我运行以上命令时,我得到:

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

The passed value = "2" is correct, however the value "13" that comes up inside the library function is wrong. 传递的值=“ 2”是正确的,但是库函数中出现的值“ 13”是错误的。 Why is the passed value dereferenced in the same way coming different from calling function and different in called function? 为什么以相同的方式解引用的传递值与调用函数不同,而被调用函数又不同呢?

Can you add code to print out the memory address of arg_thread and t. 您可以添加代码以打印出arg_thread和t的内存地址吗? I have a feeling what is going on is that your pointer is being sliced in half by a cast. 我感觉发生了什么事,就是您的指针被演员表切成了两半。 Is MyThreadJoin being forward declared in MyLib.h correctly? 在MyLib.h中正确声明了MyThreadJoin吗? Are you compiling your code as 64 bit? 您是否将代码编译为64位?

[edit] I just saw your comment where you were creating t. [edit]我刚刚在创建t的地方看到了您的评论。 It looks like you are allocating it on the stack,(not the heap). 看起来您是在堆栈(而不是堆)上分配它。 When you go up a stack frame, it's memory hasn't been overwritten. 当您上升一个堆栈帧时,它的内存尚未被覆盖。 When you push a new function on to the stack, it overwrites the memory on t. 当您将新函数压入堆栈时,它将覆盖t上的内存。 The simple solution is to malloc the struct in your construction function. 简单的解决方案是在构造函数中分配结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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