Skip to main content

IAR Embedded Workbench for Arm 9.70.x

CERT-ERR33-C_a

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 standard library functions without checking for errors in return value and/or errno.

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

int utf8_to_wcs(wchar_t *wcs, size_t n, const char *utf8,
                size_t *size) {
    if (NULL == size) {
        return -1;
    }
    setlocale(LC_CTYPE, "en_US.UTF-8");
    *size = mbstowcs(wcs, utf8, n);
    return 0;
}

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

#include <locale.h>
#include <stdlib.h>

int utf8_to_wcs(wchar_t *wcs, size_t n, const char *utf8,
                size_t *size) {
    if (NULL == size) {
        return -1;
    }
    const char *save = setlocale(LC_CTYPE, "en_US.UTF-8");
    if (NULL == save) {
        return -1;
    }

    *size = mbstowcs(wcs, utf8, n);

    if(*size == (size_t)(-1)) {
        /* handle error */
    }

    if (NULL == setlocale(LC_CTYPE, save)) {
        return -1;
    }
    return 0;
}