Memory allocated dynamically with ``++calloc(...)++``, ``++malloc(...)++``, ``++realloc(...)++`` or ``++new++`` should be released when it's not needed anymore. Failure to do so will result in a memory leak that could bring the box to its knees.


This rule raises an issue when memory is allocated and not freed in the same function. Allocated memory is ignored if a pointer to it is ``++return++``ed to the caller or stored in a structure that's external to the function.


== Noncompliant Code Example

----
int fun() {
  char* name = (char *) malloc (size);
  if (!name) {
    return 1;
  }
  // ...
  return 0; // Noncompliant, memory pointed by "name" has not been released
}
----


== Compliant Solution

----
int fun() {
  char* name = (char *) malloc (size);
  if (!name) {
    return 1;
  }
  // ...
  free(name);
  return 0;
}
----


== See

* https://cwe.mitre.org/data/definitions/401.html[MITRE, CWE-401] - Improper Release of Memory Before Removing Last Reference ('Memory Leak')
* https://wiki.sei.cmu.edu/confluence/x/FtYxBQ[MEM00-C.] - Allocate and free memory in the same module, at the same level of abstraction
* https://wiki.sei.cmu.edu/confluence/x/GNYxBQ[CERT, MEM31-C.] - Free dynamically allocated memory when no longer needed



ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
