How to fix strict-aliasing with functions that use void**

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

 



I'm a newbie to GCC 4.x and I am getting lots of warnings about type punning with code that use void** (I am using -O3). I have functions declared to perform dynamic memory allocation that use void**:

  bool RiMalloc(void **pBlock, int nSize);
  void RiFree(void **pBlock);

So, for example, we call the functions thus:

  typedef struct {
     int x;
     int y;
  } tWibble;

  tWibble* void test_func(void)
{ tWibble* pZ = NULL;
     if (RiMalloc(&pZ, sizeof(tWibble)))
     {
        pZ->x = 5;
        pZ->y = 10
     }
     return pZ;
  }

Compiling this code with strict-aliasing enabled produces a warning.

Putting a void* cast in front of &pZ in the RiMalloc() call stops the warning being produced, but I am unsure as to whether I am really fixing the problem or hiding it:

  tWibble* void test_func(void)
{ tWibble* pZ = NULL;
     if (RiMalloc((void*)&pZ, sizeof(tWibble)))
     {
        pZ->x = 5;
        pZ->y = 10
     }
     return pZ;
  }


Another way that stops the warning being produced is to create another pointer with void * type:

  tWibble* void test_func(void)
  {
     void *pvZ = NULL;
     if (RiMalloc(&pvZ, sizeof(tWibble)))
     {
        tWibble* pZ;
pZ = pvZ;
        pvZ->x = 5;
        pvZ->y = 10
     }
     return pvZ;
  }

But isn't this creating an aliasing problem, as now I have two pointers of different types that point to the same memory location? What is the correct way of fixing these strict-aliasing warnings without changing the functions API?
Using a union of the pointers appears to be invalid.
I really do not want to change the RiMalloc() and RiFree() interface as it is used extensively in our code. I am no expert on the assembly language produced for the processor I am using, so I am dubious of my ability to check the compiler output.

Thanks for your help,
Steve.

[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