Skip to main content

IAR Embedded Workbench for RX 5.20

LIB-strncat-overrun-pos

In this section:
Synopsis

A call to strncat might cause a destination buffer overrun.

Enabled by default

No

Severity/Certainty

Medium/Medium

mediummedium.png
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 append, as determined by the position of the null terminator in the source buffer or the size passed as the third argument to strncat, an overflow might occur resulting in undefined behavior and runtime errors.

Coding standards
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 <string.h>
#include <stdlib.h>

void example(int d) {
  char * a = malloc(sizeof(char) * 5);
  char * b = malloc(sizeof(char) * 100);
  int c;
  if (d) {
    c = 10;
  } else {
    c = 5;
  }
  strcpy(a, "0123");
  strcpy(b, "45678901234");
  strncat(a, b, c);
}

The following code example passes the check and will not give a warning about this issue:

#include <string.h>
#include <stdlib.h>

void example(int d) {
  char * a = malloc(sizeof(char) * 5);
  char * b = malloc(sizeof(char) * 100);
  int c;
  if (d) {
    c = 2;
  } else {
    c = 3;
  }
  strcpy(a, "0123");
  strcpy(b, "45678901234");
  strncat(b, a, c);
}