AutosarC++18_10-M18.0.3¶
The library functions abort, exit, getenv and system from library <cstdlib> shall not be used
Required inputs: IR
std::atoi, std::atof, and std::strtol provide no portable error
reporting. Use safe functions like std::stoi (which throws exceptions) or std::from_chars (which
provides error codes) to properly detect and handle conversion failures.
Bad code (unsafe conversion):
std::string str = "not_a_number"; int value = std::atoi(str.c_str()); // ERROR: returns 0 silently double d = std::atof(str.c_str()); // ERROR: returns 0.0 without reporting error // No way to distinguish between "0" and failed conversion
Good code (using std::stoi with exception):
std::string str = "42";
try {
int value = std::stoi(str); // OK: throws on invalid format
double d = std::stod(str); // OK: throws on failure
} catch (const std::invalid_argument& e) {
std::cerr << "Conversion failed: " << e.what() << std::endl;
}
Good code (using std::from_chars):
std::string str = "123";
int value;
auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
if (ec == std::errc() && ptr == str.data() + str.size()) {
// OK: conversion successful
} else {
// Handle error explicitly
}
Good code (using strtol)
char *end;
const char* str = "123";
errno = 0;
const long value = strtol(str, &end, 10);
if (errno == 0 && str != end) {
printf("value: %ld\n", value); // OK: conversion successful
} else {
printf("conversion failed\n");
}
Note
For legal reasons, this rule’s description is not part of the public documentation.