From 8bee03c4abc563c945cfb87608896d23a331a006 Mon Sep 17 00:00:00 2001 From: "oetelaar.automatisering@gmail.com" Date: Thu, 16 May 2013 09:45:16 +0000 Subject: [PATCH] Clean the Util::strToL() number conversion, add proper error check and reporting, possible fix for issue #19 --- darkice/trunk/src/Util.cpp | 34 +++++++++++++++++++++------------- darkice/trunk/src/Util.h | 4 +--- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/darkice/trunk/src/Util.cpp b/darkice/trunk/src/Util.cpp index afedb14..60e637b 100644 --- a/darkice/trunk/src/Util.cpp +++ b/darkice/trunk/src/Util.cpp @@ -33,6 +33,12 @@ #include "config.h" #endif +#ifdef HAVE_ERRNO_H +#include +#else +#error need errno.h +#endif + #ifdef HAVE_STRING_H #include #else @@ -245,21 +251,23 @@ Util :: strEq( const char * str1, * Convert a string to a long integer *----------------------------------------------------------------------------*/ long int -Util :: strToL( const char * str, - int base ) throw ( Exception ) +Util :: strToL( const char *str) throw ( Exception ) { - long int val; - char * s; - - if ( !str ) { - throw Exception( __FILE__, __LINE__, "no str"); - } - - val = strtol( str, &s, base); - if ( s == str || val == LONG_MIN || val == LONG_MAX ) { - throw Exception( __FILE__, __LINE__, "number conversion error"); - } + long int val; + char *end; + if ( NULL == str ) + throw Exception( __FILE__, __LINE__, "null pointer parameter, not string"); + + errno = 0; // set it, strtol() can change it + val = strtol( str, &end, 10); + + 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; } diff --git a/darkice/trunk/src/Util.h b/darkice/trunk/src/Util.h index ba44abe..ac88fac 100644 --- a/darkice/trunk/src/Util.h +++ b/darkice/trunk/src/Util.h @@ -187,13 +187,11 @@ class Util * Convert a string to long. * * @param str the string to convert. - * @param base numeric base of number in str. * @return the value of str as a long int * @exception Exception */ static long int - strToL ( const char * str, - int base = 10 ) throw ( Exception ); + strToL ( const char * str) throw ( Exception ); /** * Convert a string to double.