Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the memory content of a union

Suppose I define a union like this:

#include <stdio.h>

int main() {
    union u {
        int i;
        float f;
    };
    union u tst;
    tst.f = 23.45;

    printf("%d\n", tst.i);

    return 0;
}

Can somebody tell me what the memory where tst is stored will look like?

I am trying to understand the output 1102813594 that this program produces.

like image 463
Moeb Avatar asked Mar 04 '10 04:03

Moeb


2 Answers

It depends on the implementation (compiler, OS, etc.) but you can use the debugger to actually see the memory contents if you want.

For example, in my MSVC 2008:

0x00415748  9a 99 bb 41

is the memory contents. Read from LSB on the left side (Intel, little-endian machine), this is 0x41bb999a or indeed 1102813594.

Generally, however, the integer and float are stored in the same bytes. Depending on how you access the union, you get the integer or floating point interpretation of those bytes. The size of the memory space, again, depends on the implementation, although it's usually the largest of its constituents aligned to some fixed boundary.

Why is the value such as it is in your (or mine) case? You should read about floating-point number representation for that (look up ieee 754)

like image 141
Eli Bendersky Avatar answered Sep 21 '22 12:09

Eli Bendersky


The result is depends on the compiler implementation, But for most x86 compilers, float and int will be the same size. Wikipedia has a pretty good diagram of the layout of a 32 bit float http://en.wikipedia.org/wiki/Single_precision_floating-point_format, that can help to explain 1102813594.

If you print out the int as a hex value, it will be easier to figure out.

printf("%x\n", tst.i);
like image 5
John Knoeller Avatar answered Sep 23 '22 12:09

John Knoeller