Aliasing/Torek's strtod() experience

A

Adam Warner

Hi all,

Message ID <[email protected]> is one of many informative
articles by Chris Torek about C. The particular message discusses aliasing
and concludes with this paragraph:

Under these strict type-aliasing rules, casting from (e.g.) "int *" to
"short *" is not only quite suspicious, it is also likely to cause
puzzling behavior, at least if you expect your "short *" to access or
modify your "int". Even the time-honored, albeit dubious, practise of
breaking a 64-bit IEEE "double" into two 32-bit integers (int or long
depending on the CPU involved) via a union need not work, and sometimes
does not. (We had a problem with strtod() not working right because of
code just like this. It worked in older gcc compilers, and eventually
failed when gcc began doing type-specific alias analysis and
optimizations.)

The code I've written below breaks an 8 byte double into two 4 byte signed
integers via a union. How should this code be modified so it conforms to
C's aliasing rules?

#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

union u {
double f64;
uint32_t u32[2];
};

int main() {
assert(sizeof(double)==8);
double val=strtod("1.23", NULL);
printf("%i %i\n", ((union u) val).u32[0], ((union u) val).u32[1]);
return 0;
}

Many thanks,
Adam
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top