3

I have the following union

typedef union rem{
    int addr;
    char addrbuf[32];
} foo;

A sizeof on the union provides the following output

foo addr;
printf("size is: %d\n",sizeof addr);

size is: 32

Does it mean that a union allocates or needs the memory equal to biggest element in the union at definition ?

cmidi
  • 1,880
  • 3
  • 20
  • 35
  • 1
    Yes. Depends on the max size member in it. – Sunil Bojanapally Jan 21 '15 at 18:29
  • Yes, up to alignment. – Eugene Sh. Jan 21 '15 at 18:32
  • Are you truly defining a union instance or are you mapping a pointer to a struct that contains this union, where the first struct member (m_eAddrType) tells you how to interpret the next member of the struct that is this union (i.e. look at .addr vs. looking at .addrBuff? I have implemented this "variant record" data-structure using struct that contain a union. – franji1 Jan 21 '15 at 18:48

2 Answers2

8

Does it mean that a union allocates or needs the memory equal to biggest element in the union at definition ?

Yes. Memory for the largest member is allocated. That's why the members of a union are stored at the same location.

Assuming int requires 4 bytes, for union

union{
    char c;
    int i;
} U; 

memory will be allocated as:

enter image description here

Note that how c and i overlap. In fact c is first byte of i.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

Memory occupied by union unlike structure will be memory for the largest member of the union. But depending on the implementation there might be extra padding at the end so there is no guarantee that the size of a union = size of the largest member. So you can say size of union will be atleast the size of the largest member in the union.

Side note: Since the memory is shared between all the members of the union only one member is active at a time.

Gopi
  • 19,784
  • 4
  • 24
  • 36