Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strtol() returns an incorrect value

I've got a weird one here. strtol, atol and atoi all return an incorrect value when I pass in the following string:

long test = strtol("3087663490", &p, 10);

According to my debugger it returns 2147483647. I'm completely stumped on this. Any advice?

like image 714
zander Avatar asked Mar 30 '11 22:03

zander


2 Answers

Your value is larger than what a signed long type can represent. Try:

unsigned long test = strtoul("3087663490", &p, 10);

(You're getting 2147483647 since it is LONG_MAX or 0x7FFFFFFF)

like image 200
yan Avatar answered Oct 04 '22 04:10

yan


Correctly testing for errors from strtol() is tricky. You need code similar to the below:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int main()
{
    char *n = "3087663490";
    char *p;
    long test;

    errno = 0;
    test = strtol(n, &p, 10);

    if (p == n)
        printf("No digits found.\n");
    else if ((test == LONG_MIN || test == LONG_MAX) && errno == ERANGE)
        printf("Value out of range.\n");
    else
        printf("Value is %ld\n", test);

    return 0;
}

Running this shows what your problem is - Value out of range.. Use a wider type, like long long (and strtoll()).

like image 42
caf Avatar answered Oct 04 '22 03:10

caf