You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 12 Next »

The three types char, signed char, and unsigned char are collectively called the character types. Compilers have the latitude to define char to have the same range, representation, and behavior as either signed char or unsigned char. Irrespective of the choice made, char is a separate type from the other two and is not compatible with either.

Use plain char for character data for compatibility with standard string handling functions.

The only permissible operators on plain char types are assignment and equality operators (=, ==, != ).

Non-Compliant Code Example

The following non-compliant code example simply illustrates calling the standard string handling function strlen() with a plain character string, a signed character string, and an unsigned character string:

#include <string.h>

int main(void) {
  size_t len;
  char cstr[] = "char string";
  signed char scstr[] = "signed char string";
  unsigned char ucstr[] = "unsigned char string";

  len = strlen(cstr);
  len = strlen(scstr);  /* warns when char is unsigned */
  len = strlen(ucstr);  /* warns when char is signed */
  return 0;
}

Compiling at high warning levels in compliance with [MSC00-A. Compile cleanly at high warning levels] causes warnings to be issued when converting from unsigned char[] to char const * when char is signed and from signed char[] to char const * when char is defined to be unsigned. Casts are required to eliminate these warnings, but excessive casts can make code difficult to read and hide legitimate warning messages.

If this C code were to compiled using a C++ compiler, conversions from unsigned char[] to char const * and from signed char[] to char const * would be be flagged as errors requiring casts.

Compliant Solution

The compliant solution uses plain char for character data.

#include <string.h>

int main(void) {
  size_t len;
  char cstr[] = "char string";

  len = strlen(cstr);
  return 0;
}

Risk Assessment

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

STR07-A

1 (low)

1 (unlikely)

2 (medium)

P2

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[ISO/IEC 9899-1999]] Section 6.2.5, "Types"
[[MISRA 04]] Rule 6.1, "The plain char type shall be used only for the storage and use of character values"


STR06-A. Don't assume that strtok() leaves the parse string unchanged      07. Characters and Strings (STR)      

  • No labels