Skip to main content

IAR Embedded Workbench for Arm 9.70.x

SEC-BUFFER-strncmp-overrun-pos

In this section:
Synopsis

A call to strncmp might cause a buffer overrun.

Enabled by default

No

Severity/Certainty

High/Medium

highmedium.png
Full description

Passing an incorrect string length to strncmp might cause a buffer overrun. Strncmp limits the number of characters it compares to the number of characters passed as its third argument, to prevent buffer overruns with non-null terminated strings. However, if the number of characters passed exceeds the length of the two strings, and none of these strings is null terminated, then it will overrun. Make sure the length passed to strncmp is correct. You might need to perform an comparison before calling strncmp.

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 <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);
}