Strtod () function by David M. Gay dtoa.c

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

Being there, I also wanted to use the strtod () function from the aforementioned source, the intended benefit is to get consistent results across platforms. However, strtod calls cause memory protection problems. Does anyone know what you might need to get it working?

+3


source to share


1 answer


You will need to call strtod

appropriately, especially taking care of the second parameter. This parameter must be the address of a pointer to char, and it is set to point to the first character of an unprocessed input string strtod

. If you pass in a pointer instead of a pointer address and that pointer is not initialized with something that could be writeable memory (for example NULL

), you are likely to have a runtime 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);
}

      

+1


source







All Articles