Qt-Autosar-A21.8.1

Arguments to character-handling functions shall be representable as an unsigned char

Required inputs: IR

Rationale

This rule applies to the character handling functions in <cctype>. They all take an int parameter as input and specify that its value either shall be EOF or otherwise shall be representable as an unsigned char. On platforms where char is signed, it can have negative values that are not representable as an unsigned char, so that passing a char to such a function can result in undefined behavior.

Thus, this rule mandates that all character arguments passed to such functions shall be explicitly cast to unsigned char.

Note: Of all the functions in <cctype>, isdigit and isxdigit are the only ones whose behavior does not depend on the currently installed locale. See A18-0-3 in section 6.18.0 for a rule concerning the setlocale function.

Example
// $Id: A21-8-1.cpp 312606 2018-03-21 09:52:14Z jan.babst $
    #include <algorithm>
    #include <cctype>
    #include <string>

    void RemoveDigits_Bad(std::string& s)
    {
        s.erase(std::remove_if(s.begin(),
                               s.end(),
                               [](char c) {
                                   return std::isdigit(c);    // non-compliant
                               }),
                  s.cend());
    }

    void RemoveDigits_Good(std::string& s)
    {
        s.erase(std::remove_if(s.begin(),
                               s.end(),
                               [](char c) {
                                   return std::isdigit(
                                       static_cast<unsigned char>(c));        // compliant
                               }),
                s.cend());
    }
See Also
  • SEI CERT C++ Coding Standard [10]: STR37-C: Arguments to character- handling functions must be representable as an unsigned char.
  • cppreference.com [16]: Standard library header <cctype>.
  • Rule A18-0-3 in section 6.18.0

Possible Messages

Key

Text

Severity

Disabled

missing_uchar_cast

Missing explicit cast to unsigned char.

None

False

missing_uchar_cast_on_routine_literal

Missing explicit cast to unsigned char.

None

False

Options

functions

functions

Type: set[bauhaus.analysis.config.QualifiedName]

Default: {'isalnum', 'isalpha', 'isblank', 'iscntrl', 'isdigit', 'isgraph', 'islower', 'isprint', 'ispunct', 'isspace', 'isupper', 'isxdigit', 'tolower', 'toupper'}

Names of functions that require an unsigned char cast.