Skip to main content

IAR Embedded Workbench for RX 5.20

CERT-MEM30-C_a

In this section:
Synopsis

Do not access freed memory.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

Evaluating a pointer-including dereferencing the pointer, using it as an operand of an arithmetic operation, type casting it, and using it as the right-hand side of an assignment-into memory that has been deallocated by a memory management function is undefined behavior. This check is identical to MISRAC2012-Dir-4.13_d, MISRAC2012-Rule-1.3_o, SEC-BUFFER-use-after-free-all, MEM-use-free-all.

Coding standards
CERT MEM30-C

Do not access freed memory

CWE 416

Use After Free

CWE 456

Missing Initialization

CWE 672

Operation on a Resource after Expiration or Release

CWE 758

Reliance on Undefined, Unspecified, or Implementation-Defined Behavior

MISRA C:2012 Dir-4.13

(Advisory) Functions which are designed to provide operations on a resource should be called in an appropriate sequence

MISRA C:2012 Rule-1.3

(Required) There shall be no occurrence of undefined or critical unspecified behaviour

Code examples

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

#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *return_val = 0;
    const size_t bufsize = strlen(argv[0]) + 1;
    char *buf = (char *)malloc(bufsize);
    if (!buf) {
        return EXIT_FAILURE;
    }
    /* ... */
    free(buf);
    /* ... */
    strcpy(buf, argv[0]);
    /* ... */
    return EXIT_SUCCESS;
}

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

#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *return_val = 0;
    const size_t bufsize = strlen(argv[0]) + 1;
    char *buf = (char *)malloc(bufsize);
    if (!buf) {
        return EXIT_FAILURE;
    }
    /* ... */
    strcpy(buf, argv[0]);
    /* ... */
    free(buf);
    return EXIT_SUCCESS;
}