Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 828
Ladislav Avatar asked Oct 26 '25 14:10

Ladislav


1 Answers

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);
}
like image 171
Anthon Avatar answered Oct 29 '25 03:10

Anthon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!