Skip to main content

IAR Embedded Workbench for RISC-V 3.40

CERT-ERR34-C_b

In this section:
Synopsis

Detect errors when converting a string to a number.

Enabled by default

Yes

Severity/Certainty

Medium/Low

mediumlow.png
Full description

The process of parsing an integer or floating-point number from a string can produce many errors. These error conditions must be detected and addressed when a string-to-number conversion is performed using a C Standard Library function.

Coding standards
CERT ERR34-C

Detect errors when converting a string to a number

CWE 391

Unchecked Error Condition

CWE 676

Use of Potentially Dangerous Function

CWE 758

Reliance on Undefined, Unspecified, or Implementation-Defined Behavior

Code examples

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

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

void func(const char *buff) {
    char *end;
    int si;

    errno = 0;

    const long sl = strtol(buff, &end, 10);
}

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

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

void func(const char *buff) {
    char *end;
    int si;

    errno = 0;

    const long sl = strtol(buff, &end, 10);

    if (end == buff) {
        fprintf(stderr, "%s: not a decimal number\n", buff);
    } else if ('\0' != *end) {
        fprintf(stderr, "%s: extra characters at end of input: %s\n", buff, end);
    } else if ((LONG_MIN == sl || LONG_MAX == sl) && ERANGE == errno) {
        fprintf(stderr, "%s out of range of type long\n", buff);
    } else if (sl > INT_MAX) {
        fprintf(stderr, "%ld greater than INT_MAX\n", sl);
    } else if (sl < INT_MIN) {
        fprintf(stderr, "%ld less than INT_MIN\n", sl);
    } else {
        si = (int)sl;

        /* Process si */
    }
}