NO

Author Topic: strtol() incorrect behaviour if value outside range  (Read 2052 times)

nicolas.sitbon

  • Guest
strtol() incorrect behaviour if value outside range
« on: August 31, 2009, 04:29:09 PM »
Code: [Select]
#include <stdio.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>

int main(void)
{
   char const * str = "3545464543214648484544";
   char * endptr    = NULL;
   long result      = strtol(str, &endptr, 10);

   if((result == LONG_MIN  ||  result == LONG_MAX)  &&  errno == ERANGE  &&  endptr != NULL  &&  *endptr == '\0')
   {
      puts("good behaviour");
   }
   else
   {
      puts("incorrect behaviour, investigating...");
      printf("result = %ld : %s\n", result, result == LONG_MAX ? "OK" : "KO");
      printf("errno = %d : %s\n",   errno,  errno == ERANGE ? "OK" : "KO");
      printf("endptr = %s : %s\n",  endptr, endptr != NULL  &&  *endptr == '\0' ? "OK" : "KO");
   }

   return 0;
}

after conversion, endptr should point the null byte of str.