简体   繁体   中英

Dereferencing struct void pointer in C

I have a MyLib.h which has

typedef void *MyThread;

and a MyLib.c which has:

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:

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. 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. 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? Are you compiling your code as 64 bit?

[edit] I just saw your comment where you were creating 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. The simple solution is to malloc the struct in your construction function.

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