Use After Free

The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.


Demonstrations

The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.

Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.

Example One

The following example demonstrates the weakness.

#include <stdio.h>
#include <unistd.h>
#define BUFSIZER1 512
#define BUFSIZER2 ((BUFSIZER1/2) - 8)
int main(int argc, char **argv) {
  char *buf1R1;
  char *buf2R1;
  char *buf2R2;
  char *buf3R2;
  buf1R1 = (char *) malloc(BUFSIZER1);
  buf2R1 = (char *) malloc(BUFSIZER1);
  free(buf2R1);
  buf2R2 = (char *) malloc(BUFSIZER2);
  buf3R2 = (char *) malloc(BUFSIZER2);
  strncpy(buf2R1, argv[1], BUFSIZER1-1);
  free(buf1R1);
  free(buf2R2);
  free(buf3R2);
}

Example Two

The following code illustrates a use after free error:

char* ptr = (char*)malloc (SIZE);
if (err) {
  abrt = 1;
  free(ptr);
}
...
if (abrt) {
  logError("operation aborted before commit", ptr);
}

When an error occurs, the pointer is immediately freed. However, this pointer is later incorrectly used in the logError function.

See Also

Comprehensive Categorization: Memory Safety

Weaknesses in this category are related to memory safety.

SEI CERT C Coding Standard - Guidelines 08. Memory Management (MEM)

Weaknesses in this category are related to the rules and recommendations in the Memory Management (MEM) section of the SEI CERT C Coding Standard.

SFP Secondary Cluster: Faulty Resource Use

This category identifies Software Fault Patterns (SFPs) within the Faulty Resource Use cluster (SFP15).

Comprehensive CWE Dictionary

This view (slice) covers all the elements in CWE.

Weaknesses in the 2024 CWE Top 25 Most Dangerous Software Weaknesses

CWE entries in this view are listed in the 2024 CWE Top 25 Most Dangerous Software Weaknesses.

Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses

CWE entries in this view are listed in the 2023 CWE Top 25 Most Dangerous Software Weaknesses.


Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.