Re: Problem with -O3 and int to pointer (64bits)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Benjamin Grange writes:
 > Hi,
 > the following code converts a class A which is know to be of the size
 > of an int into a void*. This allow to save it in a list of void*.
 > When compiled without -O3 (or 2) it works. But with -O3 or 2, on
 > x86_64, the line intarray[1] = 0 is removed in the assembly output and
 > it doesn't work anymore.
 > Changing function topointer() into this:
 > return (void *)  (unsigned long)(*(((unsigned int *)&a)));
 > fix the problem.
 > 
 > So, is it a bug in gcc or does this does something bad?
 > Also do you know a good way to convert an int to a pointer?
 > 
 > Thank you.
 > Ben
 > 
 > /*----- code follows ------*/
 > #include <stdio.h>
 > 
 > void **listA;
 > 
 > class A {
 > public:
 >         A(int n) { x = n; }
 >         int x;
 > };
 > 
 > void *topointer(A a)
 > {
 >         unsigned int intarray[2];
 >         intarray[0] = *(((unsigned int *)&a));

This is a bug in your code.  If you really need to break the type
system by accessing an object by something other than its real type,
use a union:

  union
  {
    A A_kludge;
    unsigned int uint_kludge[2];
    void *nonsense;
  } kludge;
  
  kludge.A = a;
  ...

Andrew.

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux