Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Optimized code produced by gcc GCC 3.4.6.
.

Code Block
bgColor#FFCCCC
#include <stdio.h>

int main()
{
    short a[2];

    a[0]=0x1111;
    a[1]=0x1111;

    printf("%x %x\n", a[0], a[1]);
    return 0;
}

...

To fix the code above, you can use a union instead of a cast (note that this is a GCC extension which might not work with other compilers).

Code Block
bgColor#ccccff
#include <stdio.h>

int main()
{
    union
    {
        short a[2];
        int i;
    }u;

    u.a[0]=0x1111;
    u.a[1]=0x1111;

    u.i = 0x22222222;

    printf("%x %x\n", u.a[0], u.a[1]);
    return 0;
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ31-J

medium

probable

high low

P4 P12

L3 L1

References

GCC Known Bugs C bugs, Aliasing issues while casting to incompatible types

...