Skip to main content

IAR Embedded Workbench for RX 5.20

SEC-BUFFER-strcat-overrun

In this section:
Synopsis

A call to the strcat function will overrun the target buffer.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

A call to the strcat function will overrun the target buffer. strcat appends to the target the contents of the source string up until a null character. If the length of the source buffer is longer than the amount allocated in the destination buffer, a buffer overflow occurs. Alternatively, if the source string is not null terminated, strcat could read past the intended bytes and overflow the destination buffer. If possible, use strncat instead of strcat to set an upper bound on the number of bytes to append. You should also try to check the length of source and destination buffer before calling strcat.

Coding standards
CERT STR31-C

Guarantee that storage for strings has sufficient space for character data and the null terminator

CWE 119

Improper Restriction of Operations within the Bounds of a Memory Buffer

CWE 120

Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')

CWE 121

Stack-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(void)
{
  char *str1 = "Hello World!\n";
  char *str2 = (char *)malloc(13);
  strcpy(str2,"");
  strcat(str2,str1);
}

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

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

void example(void)
{
  char *str1 = "Hello World!\n";
  char *str2 = (char *)malloc(14);
  strcpy(str2, "");
  strcat(str2, str1);
}