Skip to main content

IAR Embedded Workbench for RISC-V 3.40

SEC-BUFFER-qsort-overrun-pos

In this section:
Synopsis

Arguments passed to qsort might cause it to overrun.

Enabled by default

No

Severity/Certainty

High/Medium

highmedium.png
Full description

A call to qsort might cause a buffer overrun. An overrun might be 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(int b) {
  int *a = malloc(sizeof(int) * 10);
  int c;
  if (b) {
    c = 3;  
  } else {
    c = 20;
  }
  qsort(a, c, 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(int b) {
  int *a = malloc(sizeof(int) * 10);
  int c;
  if (b) {
    c = 3;  
  } else {
    c = 2;
  }
  qsort(a, c, sizeof(int), &cmp);
}