LIB-strncmp-overrun-pos
Synopsis
A call to strncmp might cause a buffer overrun.
Enabled by default
No
Severity/Certainty
High/Medium

Full description
An incorrect string length passed to strncmp might cause a buffer overrun. 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. This check is identical to CERT-STR31-C_g.
Coding standards
- CERT STR31-C
Guarantee that storage for strings has sufficient space for character data and the null terminator
- 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(int d) {
char *a = malloc(sizeof(char) * 10);
char *b = malloc(sizeof(char) * 10);
int c;
if (d) {
c = 20;
} else {
c = 5;
}
strncmp(a, b, c);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <string.h>
void example(int d) {
char *a = malloc(sizeof(char) * 10);
char *b = malloc(sizeof(char) * 10);
int c;
if (d) {
c = 8;
} else {
c = 5;
}
strncmp(a, b, c);
}