Skip to content

Instantly share code, notes, and snippets.

@makiftasova
Created April 9, 2017 17:55
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 makiftasova/d680fcfe21acb519f5c210c29dac62d4 to your computer and use it in GitHub Desktop.
Save makiftasova/d680fcfe21acb519f5c210c29dac62d4 to your computer and use it in GitHub Desktop.
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */
#include <string.h>
/**
* atoi_r : a wrapper for atoi.
* atoi from stdlib.h has undefined behaviour if input does not contain
* a valid integer value. this function handles that undefined behaviour
* for non negative integers.
*
*/
int atoi_r(const char *str);
int main(int argc, char **argv){
const char * str0 = "12312313", *str1="asd";
printf("%d\n", atoi_r(str0));
printf("%d\n", atoi_r(str1));
return 0;
}
int atoi_r(const char *str){
char c;
for(size_t i = 0; i < strlen(str); ++i){
if ('0' > str[i] || str[i] > '9')
return -1;
}
return atoi(str);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment