Ladislav
Ladislav

Reputation: 987

strtod() function from David M. Gay's dtoa.c

I am using David M. Gay's dtoa() function from http://www.netlib.org/fp/dtoa.c to implement the MOLD function in Rebol3 interpreter. It works well, tested under Linux ARM, Linux X86, Android ARM, MS Windows and OS X X86.

Being at it, I also wanted to use the strtod() function from the above source, the assumed advantage being to get consistent results across different platforms. However, strtod calls cause memory protection problems. Does anybody have an idea what might be needed to make the function work?

Upvotes: 4

Views: 1360

Answers (1)

Anthon
Anthon

Reputation: 76632

You will need to call strtod in the appropriate way, especially taking care of the second parameter. That parameter should be the address of a pointer to char, and this is set to point to the first character of the input string not processed by strtod. If you pass the pointer instead of the address of the pointer and that pointer is not initialised to something that happens to be writable memory (like NULL), you are likely to have a run-time error.

int
main(int argc, char *argv[])
{
    char *endptr, *str;
    double val;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    str = argv[1];
    errno = 0;    

    val = strtod(str, &endptr);

    if (errno != 0) {
        perror("strtod");
        exit(EXIT_FAILURE);
    }

    if (endptr == str) {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }

    printf("strtod() returned %f\n", val);

    if (*endptr != '\0')        /* Not necessarily an error... */
        printf("Further characters after number: %s\n", endptr);

    exit(EXIT_SUCCESS);
}

Upvotes: 3

Related Questions