MISRA C:2012 Rule 21.18
The size_t
argument passed to any function in
<string.h>
shall have an appropriate value
Description
Rule Definition
The size_t
argument passed to any function in
<string.h>
shall have an appropriate
value.
This rule comes from MISRA C™: 2012 Amendment 1.
Rationale
The value of a size_t
argument passed to a function defined in
<string.h>
must be positive and not greater than the size
of the smallest object passed by pointer to the function. Consider this code, which
compares the strings str1
and str2
by using
the strncmp()
function
:
strncmp(lhs_string, rhs_string, num)
size_t
argument num
must be positive and
must not be greater than the size of str1
or
str2
, whichever is smaller.Otherwise, using the function can result in read or write access beyond the bounds of the function arguments.
Polyspace Implementation
Polyspace® reports a violation if a call to a memory or string function from
<string.h>
results in read or write access beyond the
bounds of its arguments. For example:
When arguments of a memory or string function are buffers lacking null-termination, violations are reported when the value passed to the size parameter is greater than the size of at least one of the buffers. Consider this code:
The calls tochar buf1[ 3 ] = "abc"; char buf2[ 6 ] = "123456"; (void) memcpy(buf2, buf1, 5); // Violation (void) memcpy(buf1, buf2, 4); // Violation
memcpy()
results in write access of memory locations beyond the bounds ofbuf1
.When arguments of a memory or string functions are null-terminated buffers or C-strings and the destination string is smaller than the source string, violation is reported if the value passed to the size argument is larger than the size of the destination string. Consider this code:
Copying 5 characters fromchar str1[] = "abc"; char str2[] = "123456"; (void) strncpy(str1, str2, 5); // Violation
str2
tostr1
results in write access of memory locations beyond the bounds ofstr1
. For null-terminated buffers or C-strings, violations are not reported when the destination string is larger than the source string, regardless of the size argument.
Polyspace checks for violations of this rule when memory and string functions
from <string.h>
are called, including:
memchr()
, memcmp()
,
memcpy()
, memmove()
,
memset()
, strncat()
,
strncmp()
, strncpy()
,
strxfrm()
. If the sizes of the argument buffers or strings
are not known when these functions are called, Polyspace does not report a violation.
Troubleshooting
If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Standard libraries |
Category: Mandatory |
AGC Category: Mandatory |
Version History
Introduced in R2017a