Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I handle "cast from ‘void*’ to ‘int’ loses precision" when compiling 32-bit code on 64-bit machine?

I have a package that compiles and works fine on a 32-bit machine. I am now trying to get it to compile on a 64-bit machine and find the following error-

 error: cast from ‘void*’ to ‘int’ loses precision 

Is there a compiler flag to suppress these errors? or do I have to manually edit these files to avoid these casts?

like image 780
badkya Avatar asked Jan 08 '10 01:01

badkya


People also ask

What is the size of a pointer to an int on a 64 bit architecture?

The pointer weighs 4 bytes on a 32-bit architecture and 8 bytes on a 64-bit architecture.

Can you cast a pointer to an int?

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

What does casting to void do C++?

Casting an expression to void explicitly throws away that expression's value. This tells readers that the programmer intended to write a do-nothing expression.


2 Answers

The issue is that, in 32bits, an int (which is a 32bit integer) will hold a pointer value.

When you move to 64bit, you can no longer store a pointer in an int - it isn't large enough to hold a 64bit pointer. The intptr_t type is designed for this.

like image 124
Reed Copsey Avatar answered Sep 23 '22 23:09

Reed Copsey


Your code is broken. It won't become any less broken by ignoring the warnings the compiler gives you.

What do you think will happen when you try to store a 64-bit wide pointer into a 32-bit integer? Half your data will get thrown away. I can't imagine many cases where that is the correct thing to do, or where it won't cause errors.

Fix your code. Or stay on the 32-bit platform that the code currently works on.

If your compiler defines intptr_t or uintptr_t, use those, as they are integer types guaranteed to be large enough to store a pointer.

If those types are not available, size_t or ptrdiff_t are also large enough to hold a pointer on most (not all) platforms. Or use long (is typically 64-bit on 64-bit platforms on the GCC compiler) or long long (a C99 types which most, but not all compilers, support in C++), or some other implementation-defined integral type that is at least 64 bits wide on a 64-bit platform.

like image 27
jalf Avatar answered Sep 23 '22 23:09

jalf