Strict aliasing, int aliased with struct containing int

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

 



Hello!

I'm trying to understand strict aliasing rules, and I have some
questions. Of course, I tried googling a lot first, but my
understanding contradicts with GCC behavior, so I got stucked.

It's worth noting that I'm using GCC 4.9.2 on x86_64 and write code in
C. I compile it with -O3, so -fstrict-aliasing is implied.

According to C99 (6.5/7):


An object shall have its stored value accessed only by an lvalue
expression that has one of the following types:
- a type compatible with the effective type of the object,
<...>
- an aggregate or union type that includes one of the aforementioned
types among its members (including, recursively, a member of a
subaggregate or contained union), or
<...>


As far as I understand this text, it's allowed to access int object
using pointer to struct that contains int field. But running the
following code on my machine shown unexpected results:


#include <stdio.h>

int global;

struct aggregate {
        int value;
        char arr[1];
};

int modify(struct aggregate *param)
{
        global = 1;
        param->value = 2;
        return global;
}

int main()
{
        printf("%d\n", modify((struct aggregate *)&global));
        return 0;
}


I access the same int object two ways:
- via variable "global"
- via field "value" of "struct aggregate" by pointer "param"

As far as I understood, according to C99, struct type that includes
int may be used to access int object. But the test program prints "1"
when I expect it to print "2". And if I remove "char arr[1]" field
from struct, the test program prints "1" as expected. I can't
understand where I went wrong.

Please shed some light on this strange behavior.

Thanks in advance,
Maxim Mikityanskiy



[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