简体   繁体   中英

C, casting an array of structs passed through a void pointer

I am stuck in a simple pointer/casting problem:

I am try to pass as a argument to the pthread function in pthread_create an array of 2 structs. Here is the code:

struct sockaddr_in addr_left, addr_right;
struct sockaddr_in* addr_vec [2] = {&addr_left, &addr_right};
pthread_create (&thread_forward,   NULL, thread_func_forward, (struct sockaddr**)addr_vec); 

Inside thread_func_forward:

void * thread_func_forward (void * argv) {
  struct sockaddr_in* addr_left = ((struct sockaddr_in*)argv + 0);
  struct sockaddr_in* addr_right = ((struct sockaddr_in*)argv + 1);
}

For some reason it does not work properly, the program can execute the last lines without segmentation fault but when I access to the members of the structs, they are completely changed

You are not casting your thread argument back to the right type. Your code casts the thread argument to a struct sockaddr_in * , but that is not the right type. addr_vec is an array of pointers, and so addr_vec will decay into a pointer to a pointer.

Since you are passing in a pointer to a pointer, so you should cast it as such in your thread function. Then, you need to dereference it to obtain the pointer that you want.

  struct sockaddr_in* addr_left = *((struct sockaddr_in**)argv + 0);
  struct sockaddr_in* addr_right = *((struct sockaddr_in**)argv + 1);

The fact that those are pointers to local automatic variables from the function creating the threads may or may not be a problem. It depends on whether that function waits for the threads to complete before those variables fall out of scope.

Your addr_vec lives in automatic storage (ie on the stack), but there is no indication that you've taken any steps to ensure the lifespan of the variable lasts long at least as far as the point where you access them in the thread.

In short you need to either dynamically allocate before creating the thread and then release it within the thread, or use synchronisation primitives to prevent the function you create the thread in from returning before you've taken a copy in the thread itself.

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