SEC-BUFFER-strncat-overrun
Synopsis
A call to strncat causes a buffer overrun.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
Calling strncat with a destination buffer that is too small will cause a buffer overrun. strncat takes a destination buffer as its first argument. If the remaining space of this buffer is smaller than the number of characters to be appended, as determined by the position of the null terminator in the source buffer or the size passed as the third argument to strncat, then an overflow might occur resulting in undefined behavior and potential runtime errors. Make sure that the length passed to strncat is correct. You might need to perform an comparison before calling strncat.
Coding standards
- CWE 119
Improper Restriction of Operations within the Bounds of a Memory Buffer
- CWE 121
Stack-based Buffer Overflow
- CWE 122
Heap-based Buffer Overflow
Code examples
The following code example fails the check and will give a warning:
#include <string.h>
#include <stdlib.h>
void example(void) {
char * a = malloc(sizeof(char)*9);
strcpy(a, "hello");
strncat(a, "world", 6);
}
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 * a = malloc(sizeof(char)*11);
strcpy(a, "hello");
strncat(a, "world", 6);
}