Skip to main content

IAR Embedded Workbench for Arm 9.70.x

SEC-BUFFER-strncat-overrun-pos

In this section:
Synopsis

A buffer overrun might be caused by a call to strncat.

Enabled by default

No

Severity/Certainty

High/Medium

highmedium.png
Full description

Calling strncat with a destination buffer that is too small causes 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(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);
}