Back Midas Rome Roody Rootana
  Midas DAQ System  Not logged in ELOG logo
Entry  10 May 2007, Konstantin Olchanski, Info, RHEL5/SL5 success! 
    Reply  03 Jul 2007, Ryu Sawada, Info, RHEL5/SL5 success! 
Message ID: 393     Entry time: 03 Jul 2007     In reply to: 374
Author: Ryu Sawada 
Topic: Info 
Subject: RHEL5/SL5 success! 
> P.S. For the record, the compiler produces two sets of warnings:
> - warning: dereferencing type-punned pointer will break strict-aliasing rules
> (I do not understand the meaning of the second warning. type-punned pointer, huh?)

This is because strict aliasing rule is broken in this code.

In ISO C++99 standard, it is illegal to create two pointers of different types referring to the same address.
Even a code breaks the rule, it compiles, but the result is undefined.

For example following code gives different results depends on -O2 is used or not, because -O2 includes -fstrict-aliasing option.
When -fstrict-aliasing is used, compiler can optimize the code assuming the strict aliasing rule.
#include <stdio.h>
int main(){
   int ii = 1;
   float* ff = (float*)&ii;
   *ff = 2;
   printf("%d\n", ii);
   return 0;

GCC warns this kind of code with a message like,
warning: dereferencing type-punned pointer will break strict-aliasing rules
The behavior differs also depending on compilers. GCC3 does not warn, while GCC4 warns. (GCC3 is the default on SL4, while GCC4 is
the default on SL5)
And results are different. GCC3 gives 0, while GCC4 gives 1.
#include <stdio.h>

typedef struct xxx {int ii;} XX;
int main(){
   XX a;
   a.ii = 1;
   *(short*)&a.ii = 0;
   printf("%d\n", a.ii);
   return 0;

More dangerous thing is that compilers do not always warn about it. For example, following code compiles without warnings even
when you use -Wall (including -Wstrict-aliasing). But the result changes depending on compile flags or compiler versions.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(){
   int *ii = (int*)malloc(8);
   ii[0] = 1;
   ii[1] = 2;
   float* ff = (float*)ii;
   ff[0] = 3;
   ff[1] = 4;
   printf("%d %d\n", ii[0], ii[1]);
   return 0;

A safer way is disabling -fstrict-aliasing compile flag. For example, you may change compile flag for midas like "-O2 -fno-strict-
Disadvantage is that there is a possibility that the speed is decreased.

The best way is modifying code to be in the strict aliasing rule.

Best regards
ELOG V3.1.4-2e1708b5