Skip to main content

IAR Embedded Workbench for RX 5.20

MISRAC2012-Rule-22.1_a

In this section:
Synopsis

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

Enabled by default

Yes

Severity/Certainty

High/Low

highlow.png
Full description

A memory leak due to incorrect deallocation was detected. This check is identical to MEM-leak, SEC-BUFFER-memory-leak, CERT-MEM31-C.

Coding standards
CERT MEM31-C

Free dynamically allocated memory exactly once

CWE 401

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

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>

int main(void) {
  int *ptr = (int *)malloc(sizeof(int));
  
  ptr = NULL; //losing reference to the allocated memory

  free(ptr);

  return 0;
}

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

#include <stdlib.h>

int main(void) {
    int *ptr = (int*)malloc(sizeof(int));
    if (rand() < 5) {
        free(ptr);
    } else {
        free(ptr);
    }
    return 0;
}