简体   繁体   中英

Casting a pointer to int and a warning?

I got this warning when building beta release of SageMath 6.1 on OSX 10.9.1, with 64 bit processor:

extra.cc:940:30: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

Can you give an example of the command which can cause this kind of warning?

The post here says that there is no way to do it:

void *ptr = ...;
int x = (int)ptr;
...
ptr = (void *)x;

which is invalid according to the source.

Gcc version

$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

The link is correct. The issue is that neither an int nor a pointer has a standard size, but on a 32-bit system they are most likely to both be 32-bits, whereas on a 64-bit system, a pointer is 64-bits wide while an int is still likely 32-bits.

Can you give an example of the command which can cause this kind of warning?

On a 64-bit system using glibc, take an int and cast its value to a pointer:

int x;
void *p = (void*)x;   

Of course, if the issue is that pointers are twice the size of ints, this all by itself isn't a problem, it just throws a warning. The reason this kind of thing should throw a warning is that it could , in a "not all by itself" context, indicate a serious mistake.

So, it's not a good programming practice but it does not have to indicate a real error -- eg, p += (void*)x will do the same thing, and this is more obviously likely innocuous, although the cast is unnecessary (and causes the warning).

I notice all kinds of (hopefully) innocent warnings like this when compiling even widely used, well aged software. You just have to trust that the people who've put it together are aware of this and aren't phased because they are sure there isn't a real issue, just a spurious warning. They could almost certainly still eliminate them, but GCC is notoriously picky ( suggest YET MORE parentheses... ), and not everyone cares, particularly on portable projects that may be more often built elsewhere.

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