Rajsi
Rajsi

Reputation: 29

Memory Allocation for union

In the following code

#include <stdio.h>

int main() {
    union a {
        int i;
        char ch[2];
    };
    union a u;
    int b;
    u.ch[0] = 3;
    u.ch[1] = 2;
    printf("%d,%d,%d\n", u.ch[0], u.ch[1], u.i);
    return 0;
}

The output I get is

3,2,515

Can anyone explain me why the value of i is 515?

Upvotes: 2

Views: 1860

Answers (1)

Achal
Achal

Reputation: 11921

union a {
        int i;
        char ch[2];
};
union a u; /* initially it contains gargage data */

All members of the union shares the common memory. In above case total of 4 bytes gets allocated for u because in 4 bytes(MAX memory needed) you can store both i and ch.

                        ch[1]    ch[0]
    ----------------------------------
   |     G  |   G    |   G   |  G    |  => G means garbage/junk data, because u didn't initialized 
    ----------------------------------
                                     u
  MSB                               LSB

when statement u.ch[0] = 3; executed only ch[0] initialized.

                  ch[1]    ch[0]
    --------------------------------------
   |     G  |   G    |   G   | 0000 0011 |  => G means garbage/junk data, because u didn't initialized 
    --------------------------------------
                                        u
 MSB                                   LSB

And when u.ch[1] = 2; executed next 1 bytes gets initialized as

                        ch[1]       ch[0]
    ------------------------------------------
   |     G  |   G    | 0000 0010  | 0000 0011 |  => G means garbage/junk data, because u didn't initialized 
    ------------------------------------------
                                              u
 MSB                                        LSB

As you can see above out of 4 bytes only first 2 bytes got initialized, still remaining 2 bytes are uninitialised so when you are printing u.i, its undefined behaviour.

If you want expected result then initialize then union variable first as

union a u = { 0 }; /* all 4 bytes got initialized at first instance itself, no chance of any junk data */
 u.ch[0] = 3;
 u.ch[1] = 2;

Now when you prints u.i, it prints data in whole 4 bytes which is 512 + 3 = 515 (In case of little enidian processor)

Upvotes: 4

Related Questions