Don't know where I am going wrong.
*(uint64_t *)&f
breaks the strict-aliasing rules. See Fix for dereferencing type-punned pointer will break strict-aliasing
To fix, use a memcpy()
as well answered by @dbush or a union
. A union
copes with the strict-aliasing rules.
void insert2(Buffer *buf, double f, size_t index) {
union {
double d;
uint64_t u64;
} u = { f };
insert_64(buf, u.u64, index);
}
or also use a compound literal (available since C99)
void insert3(Buffer *buf, double f, size_t index) {
// v-----------------------------------------v compound literal
insert_64(buf, (union { double d; uint64_t u64; }){.d = f}.u64, index);
}
With C11, I would add the below for future assessment of correctness.
_Static_assert(sizeof (double) == sizeof (uint64_t), "Unexpected sizes");
Note: rare platforms have differing endian per integer and FP types.