Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-MEM34-C_a

In this section:
Synopsis

Only free memory allocated dynamically.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

Freeing memory that is not allocated dynamically can result in heap corruption and other serious errors. This check is identical to MEM-free-variable, MISRAC2012-Rule-22.2_c.

Coding standards
CERT MEM34-C

Only free memory allocated dynamically

CWE 590

Free of Memory not on the Heap

MISRA C:2012 Rule-22.2

(Mandatory) A block of memory shall only be freed if it was allocated by means of a Standard Library function

Code examples

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

#include <stdlib.h>

enum { BUFSIZE = 256 };

void f(void) {
    char buf[BUFSIZE];
    char *p = (char *)realloc(buf, 2 * BUFSIZE);
    if (p == NULL) {
        /* Handle error */
    }
}

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

#include <stdlib.h>

enum { BUFSIZE = 256 };

void f(void) {
    char *buf = (char *)malloc(BUFSIZE * sizeof(char));
    char *p = (char *)realloc(buf, 2 * BUFSIZE);
    if (p == NULL) {
        /* Handle error */
    }
}