Skip to main content

IAR Embedded Workbench for RISC-V 3.40

CERT-ERR33-C_b

In this section:
Synopsis

Detect and handle standard library errors.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

The majority of the standard library functions, including I/O functions and memory allocation functions, return either a valid value or a value of the correct return type that indicates an error (for example, -1 or a null pointer). It is essential that programs detect and appropriately handle all errors in accordance with an error-handling policy. This check warns on usage of file char I/O standard library functions without checking for errors when the return value is EOF.

Coding standards
CERT ERR33-C

Detect and handle errors

CWE 252

Unchecked Return Value

CWE 253

Incorrect Check of Function Return Value

CWE 391

Unchecked Error Condition

Code examples

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

#include <stdio.h>

int main()
{
    FILE *fp = fopen("test.txt", "r");
    int ch = getc(fp);
    while (ch != EOF)
        {
            /* display contents of file on screen */
            putchar(ch);

            ch = getc(fp);
        }

    fclose(fp);

    getchar();
    return 0;
}

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

#include <stdio.h>

int main()
{
    FILE *fp = fopen("test.txt", "r");
    int ch = getc(fp);
    while (ch != EOF)
        {
            /* display contents of file on screen */
            putchar(ch);

            ch = getc(fp);
        }

    if (feof(fp))
        printf("\n End of file reached.");
    else
        printf("\n Something went wrong.");
    fclose(fp);

    getchar();
    return 0;
}