SEC-BUFFER-qsort-overrun
In this section:
Synopsis
Arguments passed to qsort cause it to overrun.
Enabled by default
Yes
Severity/Certainty
High/Medium

Full description
A buffer overrun is caused by a call to qsort. An overrun is caused by passing a buffer length that exceeds that of the buffer passed to either function, as their first argument. Make sure that a correct buffer length and size is passed to qsort. The call to qsort might need to be preceded with a comparison of the buffer length and element size.
Coding standards
- 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
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
#include <stdio.h>
int cmp(const void *a, const void *b) {
return a == b;
}
void example(void) {
int *a = malloc(sizeof(int) * 10);
qsort(a, 11, sizeof(int), &cmp);
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <stdio.h>
int cmp(const void *a, const void *b) {
return a == b;
}
void example(void) {
int *a = malloc(sizeof(int) * 10);
qsort(a, 3, sizeof(int), &cmp);
}