Skip to main content

IAR Embedded Workbench for RX 5.20

SEC-BUFFER-memory-leak-alias

In this section:
Synopsis

A memory leak is caused by incorrect deallocation.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.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.

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

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;
}