Clean the Util::strToL() number conversion, add proper error check and reporting, possible fix for issue #19

This commit is contained in:
oetelaar.automatisering@gmail.com 2013-05-16 09:45:16 +00:00
parent 00623f1ebc
commit 8bee03c4ab
2 changed files with 22 additions and 16 deletions

View File

@ -33,6 +33,12 @@
#include "config.h" #include "config.h"
#endif #endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#else
#error need errno.h
#endif
#ifdef HAVE_STRING_H #ifdef HAVE_STRING_H
#include <string.h> #include <string.h>
#else #else
@ -245,20 +251,22 @@ Util :: strEq( const char * str1,
* Convert a string to a long integer * Convert a string to a long integer
*----------------------------------------------------------------------------*/ *----------------------------------------------------------------------------*/
long int long int
Util :: strToL( const char * str, Util :: strToL( const char *str) throw ( Exception )
int base ) throw ( Exception )
{ {
long int val; long int val;
char * s; char *end;
if ( !str ) { if ( NULL == str )
throw Exception( __FILE__, __LINE__, "no str"); throw Exception( __FILE__, __LINE__, "null pointer parameter, not string");
}
val = strtol( str, &s, base); errno = 0; // set it, strtol() can change it
if ( s == str || val == LONG_MIN || val == LONG_MAX ) { val = strtol( str, &end, 10);
throw Exception( __FILE__, __LINE__, "number conversion error");
} if (end == str)
throw Exception( __FILE__, __LINE__, "number conversion error, not a decimal string");
if ((LONG_MIN == val || LONG_MAX == val) && ERANGE == errno)
throw Exception( __FILE__, __LINE__, "number conversion error, out of range of type long");
return val; return val;
} }

View File

@ -187,13 +187,11 @@ class Util
* Convert a string to long. * Convert a string to long.
* *
* @param str the string to convert. * @param str the string to convert.
* @param base numeric base of number in str.
* @return the value of str as a long int * @return the value of str as a long int
* @exception Exception * @exception Exception
*/ */
static long int static long int
strToL ( const char * str, strToL ( const char * str) throw ( Exception );
int base = 10 ) throw ( Exception );
/** /**
* Convert a string to double. * Convert a string to double.