Skip to main content

IAR Embedded Workbench for Arm 9.70.x

MEM-leak

In this section:
Synopsis

Incorrect deallocation causes memory leak.

Enabled by default

No

Severity/Certainty

High/Low

highlow.png
Full description

Memory is allocated, but then the pointer value is lost due to reassignment or its scope ending, without a guarantee of the value being propagated or the memory being freed. There must be no possible execution path during which the value is not freed, returned, or passed into another function as an argument, before it is lost. This is a memory leak. This check is identical to MISRAC2012-Rule-22.1_a, 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;
}