1014
Choose a language that provides automatic memory management.
Phase: Implementation
When freeing pointers, be sure to set them to NULL once they are freed. However, the utilization
of multiple or complex data structures may lower the usefulness of this strategy.
Demonstrative Examples
Example 1:
The following example demonstrates the weakness.
Example Language: C (Bad)
#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 2:
The following code illustrates a use after free error:
Example Language: C (Bad)
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.
Observed Examples
Reference Description
CVE-2022-20141 Chain: an operating system kernel has insufficent resource locking (CWE-413)
leading to a use after free (CWE-416).
https://www.cve.org/CVERecord?id=CVE-2022-20141
CVE-2022-2621 Chain: two threads in a web browser use the same resource (CWE-366), but
one of those threads can destroy the resource before the other has completed
(CWE-416).
https://www.cve.org/CVERecord?id=CVE-2022-2621
CVE-2021-0920 Chain: mobile platform race condition (CWE-362) leading to use-after-free
(CWE-416), as exploited in the wild per CISA KEV.
CWE Version 4.14
CWE-416: Use After Free
CWE-416: Use After Free