// 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;
}