Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-MEM31-C

In this section:
Synopsis

Free dynamically allocated memory when no longer needed.

Enabled by default

Yes

Severity/Certainty

Medium/Medium

mediummedium.png
Full description

Before the lifetime of the last pointer that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to free() with that pointer value. This check is identical to MEM-leak, MISRAC2012-Rule-22.1_a, SEC-BUFFER-memory-leak.

Coding standards
CERT MEM31-C

Free dynamically allocated memory exactly once

CWE 401

Improper Release of Memory Before Removing Last Reference ('Memory Leak')

CWE 404

Improper Resource Shutdown or Release

CWE 459

Incomplete Cleanup

CWE 771

Missing Reference to Active Allocated Resource

CWE 772

Missing Release of Resource after Effective Lifetime

MISRA C:2012 Rule-22.1

(Required) All resources obtained dynamically by means of Standard Library functions shall be explicitly released

Code examples

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

#include <stdlib.h>

enum { BUFFER_SIZE = 32 };

int f(void) {
    char *text_buffer = (char *)malloc(BUFFER_SIZE);
    if (text_buffer == NULL) {
        return -1;
    }
    return 0;
}

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

#include <stdlib.h>

enum { BUFFER_SIZE = 32 };

int f(void) {
    char *text_buffer = (char *)malloc(BUFFER_SIZE);
    if (text_buffer == NULL) {
        return -1;
    }

    free(text_buffer);
    return 0;
}