Skip to main content

IAR Embedded Workbench for RL78 5.20

SEC-BUFFER-strcpy-overrun-pos

In this section:
Synopsis

A call to the strcpy function might overrun the target buffer.

Enabled by default

No

Severity/Certainty

High/Medium

highmedium.png
Full description

A call to the strcpy function might overrun the target buffer. strcpy will copy the contents of the source string, up until the null character. If the length of the source string exceeds the intended destination, a buffer overflow occurs which might overwrite memory you did not intend to. Alternatively, if the null character is not present, strcpy might continue past the intended end of the string and read unintended memory into the buffer. If possible, use strncpy to set an upper limit on the number of bytes copied into the destination buffer. The number of bytes should be the length of the destination buffer. Alternatively, you might be able to check the length of both the source and destination buffers before calling strcpy.

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

CWE 122

Heap-based Buffer Overflow

CWE 124

Buffer Underwrite ('Buffer Underflow')

CWE 126

Buffer Over-read

CWE 127

Buffer Under-read

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