V2665. MISRA. The size argument passed to function from <string.h> should have an appropriate value.
This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C.
The value passed as an argument indicating the size for functions from the standard library (string.h) should be positive and should not exceed the size of the smallest buffer passed to the function via the pointer parameter.
The rule applies to the following functions: memchr, memcmp, memcpy, memmove, memset, strncat, strncmp, strncpy, strxfrm.
Violating this rule results in a buffer overflow. According to the 7.24.1.1 section of the C11 standard, the program behavior in this case is undefined.
The example:
#define MAX_STR 16
void foo()
{
char buffer2[MAX_STR/2];
//Using buffer2....
memset(buffer2, '\0', MAX_STR);
//Reusing buffer2....
}
In the foo() function, the buffer2 array is declared with a size of MAX_STR/2 (8 bytes). After some operations are performed on this array, the memset function is called to fill the buffer with zeros. The buffer is then reused for other data. Since the MAX_STR (16) value is passed to the memset function as the number of bytes to fill, a buffer overflow will occur. This leads to undefined behavior.
The fixed code:
void foo()
{
char buffer2[MAX_STR/2];
//Using buffer2
memset(buffer2, '\0', sizeof(buffer2));
//Reusing buffer2
}