Main Content

MISRA C++:2023 Rule 24.5.1

The character handling functions from <cctype> and <cwctype> shall not be used

Since R2024b

Description

Rule Definition

The character handling functions from <cctype> and <cwctype> shall not be used.

Rationale

The functions from <cctype> and <cwctype> are locale-dependent. Therefore, in some locales, these character handling functions do not handle extended character sets or unicode characters properly, or they can have inconsistent behavior in programs intended to run in multiple locales. These functions can also produce undefined behavior if the input character is not representable as unsigned char or is not equal to the value of the macro EOF.

Functions from the standard template library <locale> are safer to use because they correctly handle character classification and case conversion based on the locale you specify.

Polyspace Implementation

The rule checker reports a violation whenever the code uses functions from <cctype> or <cwctype>, such as islower() or iswdigit().

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <iostream>
#include <fstream>
#include <vector>
#include <cctype>


void main()
{
	std::ifstream file("example.txt");
	std::vector<char> contents;
	char ch;
	while (file.get(ch)) {
		ch = std::toupper(ch);     //Noncompliant 
		contents.push_back(ch);
	}
	file.close();
}

In this example, the code attempts to use the <cctype> function std::toupper() to convert characters from lowercase to uppercase. This can cause undefined results if the character value passed to the function is negative.

Use the functions from <locale> instead to perform the conversion.

#include <iostream>
#include <fstream>
#include <vector>
#include <locale>

int main()
{
    std::ifstream file("example.txt");
    if (!file) {
        std::cerr << "Error opening file." << std::endl;
        return 1;
    }

    std::locale loc;
    std::vector<char> contents;
    char ch;
    while (file.get(ch)) {
        ch = std::use_facet<std::ctype<char>>(loc).toupper(ch);  //Compliant
        contents.push_back(ch);
    }
    return 0;
}

Check Information

Group: Strings Library
Category: Required

Version History

Introduced in R2024b