union.cpp

// Potential union with float bug
// 
// Simplified code as example to demonstrate a potential bug when using unions with floats
//
// by feyd//godX.de
 
#include <stdint.h>
#include <stdio.h>
 
// Buggy variant class
class CVariant
{
public:
    CVariant() {}
    virtual ~CVariant() {}
 
    void SetIntValue(int64_t nValue)
    {
        m_nValue = nValue;
    }
 
    int64_t GetIntValue() const
    {
        return m_nValue;
    }
 
    void SetFloatValue(float fValue)
    {
        m_fValue = fValue;
    }
 
    float GetFloatValue() const
    {
        return m_fValue;
    }
protected:
    union
    {
        int64_t m_nValue;
        float m_fValue;
    };
};
 
// Application entry point (from libc)
int main(int argc, const char* argv[])
{
    printf("Union and float without copy operator...\r\n\r\n");
 
    // create object on heap to disable compiler optimisation
    CVariant* pVariant = new CVariant;
    CVariant* pVariantCopy = new CVariant;
 
    pVariant->SetIntValue(0xC0DE7F812345LL);
 
    *pVariantCopy = *pVariant;
 
    if(pVariantCopy->GetIntValue()!=pVariant->GetIntValue())
    {
        printf("Values are not identical:\r\n");
        printf("   %016llx -> %016llx %f -> %f\r\n", pVariant->GetIntValue(), pVariantCopy->GetIntValue(), pVariant->GetFloatValue(), pVariantCopy->GetFloatValue());
//      Print sign and exponent of float
//      printf("%d %d\r\n", n>>23, pVariantCopy->GetIntValue()>>23);
    } else {
        printf("Values are identical\r\n");
    }
 
    delete pVariantCopy;
    delete pVariant;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69