...
The atoi()
, atol()
, atoll()
, and atof()
functions convert the initial portion of a string token to int
, long int, long long int
, and double
representation representation, respectively. Except for the behavior on error ([ISO/IEC 9899:2011], s7.22.1.2), they are equivalent to
Code Block |
---|
atoi: (int)strtol(nptr, (char **)NULL, 10) atol: strtol(nptr, (char **)NULL, 10) atoll: strtoll(nptr, (char **)NULL, 10) atof: strtod(nptr, (char **)NULL) |
...
- do not need to set
errno
on an error; - have have undefined behavior if the value of the result cannot be represented;
- return 0 (or 0.0) if the string does not represent an integer (or decimal), which is indistinguishable from a correctly formatted, zero-denoting input string.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> void func(const char *buff) { char *end; int si; errno = 0; const long sl = strtol(buff, &end, 10); if (end == buff) { (void) fprintf(stderr, "%s: not a decimal number\n", buff); } else if ('\0' != *end) { (void) fprintf(stderr, "%s: extra characters at end of input: %s\n", buff, end); } else if ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno) { (void) fprintf(stderr, "%s out of range of type long\n", buff); } else if (sl > INT_MAX) { (void) fprintf(stderr, "%ld greater than INT_MAX\n", sl); } else if (sl < INT_MIN) { (void) fprintf(stderr, "%ld less than INT_MIN\n", sl); } else { si = (int)sl; /* Process si */ } } |
...
Tool | Version | Checker | Description | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Axivion Bauhaus Suite |
| CertC-ERR34 | |||||||||||||||||||
Clang |
| cert-err34-c | Checked by clang-tidy | ||||||||||||||||||
CodeSonar |
| BADFUNC.ATOF (customization) | Use of atof Users can add custom checks for uses of other undesirable conversion functions. | ||||||||||||||||||
Compass/ROSE | Can detect violations of this recommendation by flagging invocations of the following functions:
| ||||||||||||||||||||
Helix QAC |
| C5030 C++5016 | |||||||||||||||||||
Klocwork |
| CERT.ERR.CONV.STR_TO_NUM | |||||||||||||||||||
LDRA tool suite |
| 44 S | Fully implemented | ||||||||||||||||||
Parasoft C/C++test |
| CERT_C-ERR34-a | The library functions atof, atoi and atol from library stdlib.h shall not be used | ||||||||||||||||||
PC-lint Plus |
| 586 | Assistance provided | ||||||||||||||||||
| CERT C: Rule ERR34-C | Checks for unsafe Unsafe conversion from string to numeric value | String to number conversion without validation checks | PRQA QA-C++ | |||||||||||||||||
Include Page | cplusplus:PRQA QA-C++_V | cplusplus:PRQA QA-C++_V | 5016 | PRQA QA-C | |||||||||||||||||
Include Page | PRQA QA-C_v | PRQA QA-C_v | 5030 | Partially implemented(rule fully covered) | |||||||||||||||||
SonarQube C/C++ Plugin |
| S989 |
...