Skip to main content

IAR Embedded Workbench for RISC-V 3.40

LIB-fread-overrun-pos

In this section:
Synopsis

A call to fread might cause a buffer overrun.

Enabled by default

No

Severity/Certainty

Medium/Medium

mediummedium.png
Full description

A call to fread might cause an overrun due to invalid arguments. fread takes an array as its first argument, the size of elements in the array as the second argument, and the number of elements in that array as the third. If (size * count) is greater than the allocated size of the array, an overrun will occur.

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 <stdio.h>
#include <stdlib.h>

void example(int b) {
  int *a = malloc(sizeof(int) * 10);  
  int c;
  if (b) {
    c = 5;
  } else {
    c = 11;
  }
  fread(a, sizeof(int), c, NULL);
}

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

#include <stdio.h>
#include <stdlib.h>

void example(int b) {
  int *a = malloc(sizeof(int) * 10);  
  int c;
  if (b) {
    c = 10;
  } else {
    c = 5;
  }
  fread(a, sizeof(int), c, NULL);
}