Using ``++free(...)++`` or ``++delete++`` releases the reservation on a memory location, making it immediately available for another purpose. So releasing the same memory location twice can lead to corrupting the program's memory. 


A best practice to avoid this bug calls for setting just-freed pointers to ``++NULL++``, and always null-testing before a ``++free++`` or ``++delete++``.


== Noncompliant Code Example

----
void doSomething(int size) {
  char *cp = (char *) malloc(sizeof(char) * size);

  // ...
  if (condition) {
    free(cp);
  }

  free(cp);  // Noncompliant
}
----


== Compliant Solution

----
void doSomething(int size) {
  char *cp = (char *) malloc(sizeof(char) * size);

  // ...
  if (condition) {
    free(cp);
    cp = NULL; // This will prewent freeing the same memory again
  }

  free(cp); // This is OK: if the memory was freed in the if-block above, free(NULL) is a no-op
  cp = NULL; // This will prevent freeing the same memory again
}
----


== See

* https://cwe.mitre.org/data/definitions/415.html[MITRE, CWE-415] - Double Free
* https://owasp.org/www-community/vulnerabilities/Doubly_freeing_memory[OWASP, Doubly freeing memory]


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

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