V2664. MISRA. Use of the string handling functions from <string.h> should not result in accesses beyond the bounds of the objects referenced by their pointer parameters.
This diagnostic rule is based on the MISRA (Motor Industry Software Reliability Association) software development guidelines.
This diagnostic rule is relevant only for C.
Using string-handling functions from the standard library (string.h) should not result in out-of-bounds access.
The rule applies to the following functions: strcat, strchr, strcmp, strcoll, strcpy, strcspn, strlen, strpbrk, strrchr, strspn, strstr, strtok.
The use of such functions without additional checks may result 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:
char str[] = "Short";
void foo(void)
{
(void)strcpy(str, "Another, and his clue would be complete!");
}
The error occurs when calling the strcpy function, which copies a string literal to the str character array without first checking their size compatibility. Since the copied string is much longer than the target array, the data overflows the memory allocated for str, causing a buffer overflow.
The fixed code:
char str[] = "Short";
void foo(void)
{
const char* source = "Another, and his clue would be complete!";
(void)strncpy(str, source, sizeof(str) - 1);
}