Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-FIO37-C

In this section:
Synopsis

A string returned by fgets() and fgetsws() might contain NULL characters.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

A string returned by fgets() and fgetsws() might contain NULL characters. If the length of this string is then used to access the buffer, it might result in an unexpect integer wrap around leading to an out-of-bounds memory write.

Coding standards
CERT FIO37-C

Do not assume that fgets() returns a nonempty string when successful

CWE 119

Improper Restriction of Operations within the Bounds of a Memory Buffer

CWE 241

Improper Handling of Unexpected Data Type

Code examples

The following code example fails the check and will give a warning:

#include <stdio.h>
#include <string.h>
 
enum { BUFFER_SIZE = 1024 };
 
void func(void) {
  char buf[BUFFER_SIZE];
 
  if (fgets(buf, sizeof(buf), stdin) == NULL) {
    /* Handle error */
  }
  buf[strlen(buf) - 1] = '\0';
}

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

#include <stdio.h>
#include <string.h>
 
enum { BUFFER_SIZE = 1024 };
 
void func(void) {
  char buf[BUFFER_SIZE];
  char *p;
 
  if (fgets(buf, sizeof(buf), stdin)) {
    p = strchr(buf, '\n');
    if (p) {
      *p = '\0';
    }
  } else {
    /* Handle error */
  }
}