Make sure compatible values have the same type. For example, when the return value of one function is used as an argument to another function, make sure they are the same type. Ensuring compatible values have the same type allows the return value to be passed as an argument to the related function without conversion, reducing the potential for conversion errors.
Noncompliant Code Example
A source of potential errors may be traced to POSIX's tendency to overload return codes, using −1 to indicate an error condition but 0 for success and positive values as a result indicator (see ERR02-C. Avoid in-band error indicators). A good example is the
read() system call. This leads to a natural mixing of unsigned and signed quantities, potentially leading to conversion errors.
OpenSSH performs most I/O calls through a "retry on interrupt" function,
atomicio(). The following is a slightly simplified version of
atomicio.c, v 1.12 2003/07/31. The function
f() is either
This function has a large number of flaws. Pertinent to this recommendation, however, are the following:
atomicio()function returns an
ssize_t(which must be a signed type). The
ssize_ttype is a clear indication of poor interface design because a size should never be negative.
posare declared as
- The expression
n - posresults in the conversion of
posfrom a signed to an unsigned type because of the usual arithmetic conversions (see INT02-C. Understand integer conversion rules).
atomicio() function from
atomicio.c, v 1.25 2007/06/25, was modified to always return an unsigned quantity and to instead report its error via
Changes to this version of the
atomicio() function include the following:
atomicio()function now returns a value of type
posis now declared as
- The assignment
pos += (size_t)resnow requires an explicit cast to convert from the signed return value of
- The expression
n - posno longer requires an implicit conversion.
Reducing the need to use signed types makes it easier to enable the compiler's signed/unsigned comparison warnings and fix all of the issues it reports (see MSC00-C. Compile cleanly at high warning levels).
The risk in using in-band error indicators is difficult to quantify and is consequently given as low. However, if the use of in-band error indicators results in programmers' failing to check status codes or incorrectly checking them, the consequences can be more severe.
Key here (explains table format and definitions)
|[Miller 2007]||"Security Measures in OpenSSH"|