Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
atoi: (int)strtol(nptr, (char **)NULL, 10)
atol: strtol(nptr, (char **)NULL, 10)
atoll: strtoll(nptr, (char **)NULL, 10) 

However, it is better to use strtol() and related functions because atoi(), atol(), and atoll(): need not affect the value of the integer expression

  • do not need to set errno on an error

...

  • have undefined behavior if the value of the result cannot be represented

Non-Compliant Example 1

The following code converts the string stored in the static array {{buff} to a signed integer value.

Code Block

char buff [25];
int int_var;

fgets(buff, sizeof buff, stdin);
int_var = atoi(buff);

Unfortunately, atoi() and related functions lack a mechanism for reporting errors for invalid values, the behavior is undefined.

Non-Compliant Example 2

The following example using sscanf() has the same problems as atoit().

Code Block

char buff [25];
int int_var;

fgets(buff, sizeof buff, stdin);
sscanf("%d", buff, &int_var);

Compliant Solution

Code Block

char buff [25];
char *end_ptr;
long long_var;
int int_var;

fgets(buff, sizeof buff, stdin);
            
errno = 0;
        
long_var = strtol(buff, &end_ptr, 0);
        
if (ERANGE == errno) {
  puts("number out of range\n");
}
else if (long_var > INT_MAX) {
  printf("%ld too large!\n", long_var);
}
else if (long_var < INT_MIN) {
  printf("%ld too small!\n", long_var);
}
else if (end_ptr == buff) {
  printf("not valid numeric input\n");
}
else {
  int_var = (int)long_var;
}

References

  • Wiki Markup
    Jack Klein.  Bullet Proof Integer Input Using strtol(). http://home.att.net/~jackklein/c/code/strtol.html
    \[\] Section 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions