Skip to content

Instantly share code, notes, and snippets.

@cmtsij
Created September 27, 2012 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmtsij/3793290 to your computer and use it in GitHub Desktop.
Save cmtsij/3793290 to your computer and use it in GitHub Desktop.
wrapper of strtoul
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <assert.h>
unsigned long int strtoul_wrapper(const char *nptr, char **endptr, int base,int *ret_errno)
{
int set_error = 1;
unsigned long int ret_value=0;
if( nptr != NULL ){
errno = 0;
ret_value = strtoul(nptr,endptr,base);
set_error = errno;
if( nptr == *endptr ){ //no digits at all
set_error = 1;
}
}else{
set_error = 1; //nptr is NULL
}
if(set_error != 0){
set_error=1;
ret_value=0; //reset as zero when error
}
//config ret_error
if( ret_errno != NULL ){
*ret_errno = set_error;
}
return ret_value;
}
int strtoul_UNITEST(int argc,char *argv[])
{
char *next=NULL;
int err_num=0;
///////////////////////////////////////////////
// follow case should be pass
///////////////////////////////////////////////
//test 1
assert( 1 == strtoul_wrapper("1",&next,10,&err_num) && 0 == err_num );
//test 0
assert( 0 == strtoul_wrapper("0",&next,10,&err_num) && 0 == err_num );
//test -0
assert( 0 == strtoul_wrapper("-0",&next,10,&err_num) && 0 == err_num );
//WARNING case: -1 in unsigned long integer
//test -1
assert( -1lu == strtoul_wrapper("-1",&next,10,&err_num) && 0 == err_num );
//test ULONG_MAX
char ulong_max_str[256]={0};
snprintf(ulong_max_str,sizeof(ulong_max_str),"%lu",ULONG_MAX);
assert( ULONG_MAX == strtoul_wrapper(ulong_max_str,&next,10,&err_num) && 0 == err_num );
///////////////////////////////////////////////
// follow case should be fail
///////////////////////////////////////////////
//null input string
assert( 0 == strtoul_wrapper(NULL,&next,10,&err_num) && 1 == err_num );
//invalid base
assert( 0 == strtoul_wrapper("1",&next,99,&err_num) && 1 == err_num );
//invalid input string
assert( 0 == strtoul_wrapper("invalid",&next,10,&err_num) && 1 == err_num );
//overflow
char ulong_overmax_str[256]={0};
snprintf(ulong_overmax_str,sizeof(ulong_max_str),"%lu00000",ULONG_MAX); //ulong_max*100000
assert( 0 == strtoul_wrapper(ulong_overmax_str,&next,10,&err_num) && 1 == err_num );
return 0;
}
int main(int argc, char*argv[])
{
if( strtoul_UNITEST(argc,argv) == 0 ){
printf("all pass\n");
return 0;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment