SEC-BUFFER-strncpy-overrun-pos
Synopsis
The target buffer might be overrun by a call to the strncpy function.
Enabled by default
No
Severity/Certainty
Medium/Medium

Full description
The target buffer might be overrun by a call to the strncpy function. If the supplied buffer length exceeds the actual length of the destination buffer, strncpy might write past the bounds of the destination buffer. Make sure the length passed to strncpy is correct. You might need to perform a comparison before calling strncpy.
Coding standards
- CERT STR31-C
Guarantee that storage for strings has sufficient space for character data and the null terminator
- CWE 119
Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE 120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
- CWE 121
Stack-based Buffer Overflow
- CWE 122
Heap-based Buffer Overflow
- CWE 124
Buffer Underwrite ('Buffer Underflow')
- CWE 126
Buffer Over-read
- CWE 127
Buffer Under-read
- CWE 805
Buffer Access with Incorrect Length Value
Code examples
The following code example fails the check and will give a warning:
#include <string.h>
#include <stdlib.h>
void example(void)
{
char *str1 = "Hello World!\n";
char *str2 = (char *)malloc(13);
strncpy(str2,str1,14);
}
The following code example passes the check and will not give a warning about this issue:
#include <string.h>
#include <stdlib.h>
void example(void)
{
char *str1 = "Hello World!\n";
char *str2 = (char *)malloc(14);
strncpy(str2, str1, 14);
}