Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  1. It does not make sense to think of array sizes in bytes in all cases; for cases—for example, in the case of an array of integers.
  2. If the size in bytes of the array is required, it can be derived from the number of elements in the array.
  3. It is better not to add to the cognitive load of the function user by requiring the user to calculate the size in bytes of the array.

...

It is not necessary to go beyond the standard C library to find examples that violate this recommendation because the C language often prioritizes performance at the expense of robustness. The following are two examples from the C Standard, Section subclause 7.24 [ISO/IEC 9899:2011]:

Code Block
bgColor#FFcccc
langc
char *strncpy(char * restrict s1, const char * restrict s2, size_t n);
char *strncat(char * restrict s1, const char * restrict s2, size_t n);

These functions have two problems. First, there is no indication of the size of the first array, s1. As a result, it is not possible to discern within the function how large s1 is and how many elements may be written into it. Second, it appears that a size is supplied for s2, but the size_t paramenter parameter n actually gives the number of elements to copy. Consequently, there is no way for either function to determine the size of the array s2.

...

There are two notable differences between the compliant solution and the secure versions from Annex K. First, the Annex K versions use rsize_t instead of size_t, which allows the size to be compared against the reasonable limit for a single object, RSIZE_MAX. Second, the Annex K versions do not require an element count for the second array. Consequently, these functions have limited ability to validate the input for s2. However, a size value for s1 is required, so memory outside of the range for s1 should not be overwritten.

Exceptions

API02-EX1: Functions that can guarantee via their runtime-constraint handlers that no out-of-bounds read or write occurs may omit the maximum-elements argument. For instance, the s2 parameter to strcat_s() needs no max parameter.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

API02-C

highHigh

likelyLikely

highHigh

P9

L2

Related Vulnerabilities

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

...

Bibliography

[ISO/IEC 9899:2011]Annex K (normative) Bounds-checking interfaces

...

Interfaces

...