Skip to main content

IAR Embedded Workbench for RL78 5.20

CERT-MEM35-C_a

In this section:
Synopsis

Allocate sufficient memory for an object.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.png
Full description

The types of integer expressions used as size arguments to malloc(), calloc(), realloc(), or aligned_alloc() must have sufficient range to represent the size of the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur. This check is identical to MEM-malloc-sizeof-ptr.

Coding standards
CERT MEM35-C

Allocate sufficient memory for an object

CWE 680

Integer Overflow to Buffer Overflow

CWE 467

Use of sizeof() on a Pointer Type

CWE 789

Uncontrolled Memory Allocation

CWE 131

Incorrect Calculation of Buffer Size

Code examples

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

#include <stdlib.h>
#include <time.h>

struct tm *make_tm(int year, int mon, int day, int hour,
        int min, int sec) {
    struct tm *tmb;
    tmb = (struct tm *)malloc(sizeof(tmb));
    if (tmb == NULL) {
        return NULL;
    }
    *tmb = (struct tm) {
        .tm_sec = sec, .tm_min = min, .tm_hour = hour,
            .tm_mday = day, .tm_mon = mon, .tm_year = year
    };
    return tmb;
}

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

#include <stdlib.h>
#include <time.h>

struct tm *make_tm(int year, int mon, int day, int hour,
        int min, int sec) {
    struct tm *tmb;
    tmb = (struct tm *)malloc(sizeof(*tmb));
    if (tmb == NULL) {
        return NULL;
    }
    *tmb = (struct tm) {
        .tm_sec = sec, .tm_min = min, .tm_hour = hour,
            .tm_mday = day, .tm_mon = mon, .tm_year = year
    };
    return tmb;
}