dimanche 24 avril 2016

Memory position of elements in C/C++ union

I have a union in C like this:

union AUnion {
  struct CharBuf {
    char *buf;
    size_t len;
  } charbuf;
  uint8_t num;
  double fp_num;
};

My question is, can I guarantee that if given the following:

union AUnion u;

Then the following is true:

&u.num == &u.fp_num == &u.charbuf == &u

I.e they all start at the beginning of the memory segment where u is stored.

In the case of this C program compiled with gcc version 5.3.0 and -std=c11 the above is true:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

union AUnion {
    struct CharBuf {
        char *buf;
        size_t len;
    } charbuf;
    uint8_t num;
    double fp_num;
};

int main(void)
{
    union AUnion u;
    printf("%d\n", ((void*)&u) == ((void*)&u.charbuf));
    printf("%d\n", ((void*)&u.charbuf) == ((void*)&u.num));
    printf("%d\n", ((void*)&u.num) == ((void*)&u.fp_num));
}

As it prints:

1
1
1

Compiling the code above as C++11 with the same compiler results in the same output as compiling it as C11.

But is this standardized behaviour? Is it undefined? Can I rely on this behaviour with most C compilers? Can I expect this behaviour with C++ compilers as well?

Aucun commentaire:

Enregistrer un commentaire