Aliasing/Torek's strtod() experience

Discussion in 'C Programming' started by Adam Warner, Jun 29, 2005.

  1. Adam Warner

    Adam Warner Guest

    Hi all,

    Message ID <> 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
    Adam Warner, Jun 29, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Leslaw Bieniasz

    std::string and strtod()

    Leslaw Bieniasz, Sep 20, 2004, in forum: C++
    Replies:
    3
    Views:
    489
    Matt Hurd
    Sep 21, 2004
  2. Mathieu Malaterre

    strtod / setlocale

    Mathieu Malaterre, Dec 13, 2004, in forum: C++
    Replies:
    1
    Views:
    540
    Buster
    Dec 13, 2004
  3. Marky C

    strtod - Dynamic Memory?

    Marky C, Apr 1, 2004, in forum: C Programming
    Replies:
    20
    Views:
    902
    Keith Thompson
    Apr 4, 2004
  4. Adam Warner

    Aliasing/Torek's strtod() experience

    Adam Warner, Jun 29, 2005, in forum: C Programming
    Replies:
    9
    Views:
    381
    Michael Mair
    Jul 13, 2005
  5. CrazyBoB

    Chris Torek

    CrazyBoB, Jul 26, 2011, in forum: C Programming
    Replies:
    18
    Views:
    1,068
    Keith Thompson
    Aug 10, 2011
Loading...

Share This Page