Skip to main content

IAR Embedded Workbench for RH850 3.20.x

SEC-BUFFER-memory-leak

In this section:
Synopsis

A memory leak is caused by incorrect deallocation.

Enabled by default

No

Severity/Certainty

High/Low

highlow.png
Full description

Memory has been allocated, then the pointer value is lost because it is reassigned or its scope ends, without a guarantee that the value will be propagated or the memory be freed. The value must be freed, returned, or passed to another function as an argument, before it is lost, on all possible execution paths. Before a pointer is reassigned or its scope ends, the memory it points to must be freed, or a new pointer must be assigned to the memory. This check is identical to MEM-leak, MISRAC2012-Rule-22.1_a, 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;
}