简体   繁体   中英

casting an enum through a void *

I'm trying to convert some old 32 bit code to 64 bit. One of the more frequent warnings I get is:

warning: cast of pointer to integer of different size

this happens when a function calls pthread_create which accepts a void * for passing data to the new thread. The calling thread puts in that void * an enum (hence the size mismatch in 64bit). Here's the code:

typedef enum {
zero,
one,
two
}numbers_e;

some_function(...)
{
    numbers_e mydata=zero;

    ...
    pthread_create(..., (void *)mydata);
    ...
}

I managed to overcome the warning with this:

pthread_create(..., (void *)0 + my_data);

this solution is very ugly (and I'm pondering if it's better to leave the warning as is with a big remark near the code using it). Is there another solution?

your solution is not only ugly, it is undefined behaviour (UB) that could cause you problems in the future:

  • arithmetic on void* pointers is non standard and must be an extension of your compiler
  • arithmetic on pointer that don't point to valid object is UB

To avoid the first you could use (char*)0 + my_data , but this would still leave you with the second.

What you could do

  • cast your value to uintptr_t . this is a type that is guaranteed to be compatible with void* , if it exists. It exists on most modern platforms. The advatage would be that your code wouldn't compile on platforms where it doesn't exist, a clear indication that you'd have to change something, then.
  • use a pointer to the data. this is the real solution, the way pthreads are designed

For both you'd have to modify the source of the called function, though, so you'd well change it to the second, the way how this should be.

Yeah, pass the address of the object.

pthread_create(..., (void *)&mydata);

That should be safe edit as long as mydata remains available somewhere.

passing a data as a pointer is hardly a good idea, but if there is a lot of code that does it - just leave it as is. otherwise, I would pass the address as cnicutar suggested. keep in mind that if mydata scope ends before the thread begins you may have a corruption problem.

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