LIB-strncmp-overrun
Synopsis
A buffer overrun is caused by a call to strncmp.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
A buffer overrun is caused by passing an incorrect string length to strncmp. strncmp limits the number of characters it compares to the number passed as its third argument, to prevent buffer overruns with non-null-terminated strings. However, if a number is passed that is larger than the length of the two strings, and neither string is null-terminated, it will overrun.
Coding standards
- CWE 676
Use of Potentially Dangerous Function
- CWE 122
Heap-based Buffer Overflow
- CWE 121
Stack-based Buffer Overflow
- CWE 119
Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE 805
Buffer Access with Incorrect Length Value
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
#include <string.h>
void example(void) {
char *a = malloc(sizeof(char) * 10);
char *b = malloc(sizeof(char) * 10);
strncmp(a, b, 20);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <string.h>
void example(void) {
char *a = malloc(sizeof(char) * 10);
char *b = malloc(sizeof(char) * 10);
strncmp(a, b, 5);
}