Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Updated references from C11->C23

...

...

According to the C Standard, using the value of a pointer that refers to space deallocated by a call to the free() or realloc() function is undefined behavior. (See undefined behavior 177.)

Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and might be a trap representation. Fetching a trap representation might perform a hardware trap (but is not required to).

It lead to security vulnerabilities.When memory is freed, its contents may remain intact and accessible. This is because it is at the memory manager's discretion when to reallocate or recycle the freed chunk. The freed memory. When memory is freed, all pointers into it become invalid, and its contents might either be returned to the operating system, making the freed space inaccessible, or remain intact and accessible. As a result, the data at the freed location may can appear valid. However, this can change unexpectedly, leading to unintended program behavior. As a result, it is necessary to guarantee that memory is not to be valid but change unexpectedly. Consequently, memory must not be written to or read from once it is freed.

...

Noncompliant Code Example

Wiki MarkupThis example from Brian Kernighan and Dennis Ritchie \[ [Kernighan 88|AA. C References#Kernighan 88]\] illustrates both the incorrect and correct techniques for deleting items from a linked list. The incorrect solution, clearly marked as wrong in the book, is bad because {{p}} is freed before the {{p->next}} is executed, so {{p->next}} reads memory that has already been 1988] shows both the incorrect and correct techniques for freeing the memory associated with a linked list. In their (intentionally) incorrect example, p is freed before p->next is executed, so that p->next reads memory that has already been freed.

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
struct node {
  int value;
  struct node *next;
};
 
void free_list(struct node *head) {
  for (struct node *p = head; p != NULL; p = p->next)     /* WRONG */{
    free(p);
  }
}

Compliant Solution

Kernighan and Ritchie also show the correct solution. To correct this error , by storing a reference to p->next is stored   in q before freeing p.:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
struct node {
  int value;
  struct node *next;
};
 
void free_list(struct node *head) {
  struct node *q;
  for (struct node *p = head; p != NULL; p = q) {
    q = p->next;
    free(p);
}
head = NULL;}
}

...

Noncompliant Code Example

In this noncompliant code example, buff buf is written to after it has been freed. These Write-after-free vulnerabilities can be relatively easily exploited to run arbitrary code with the permissions of the vulnerable process and are seldom this obvious. Typically, allocations and frees are far removed, making it difficult to recognize and diagnose these problems.

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[]) {
  char *buff;

  buffreturn_val = 0;
  const size_t bufsize = strlen(argv[0]) + 1;
  char *buf = (char *)malloc(BUFSIZEbufsize);
  if (!buffbuf) {
     /* handle error condition */return EXIT_FAILURE;
  }
  /* ... */
  free(buffbuf);
  /* ... */
  strncpystrcpy(buffbuf, argv[1], BUFSIZE-1)0]);
  /* ... */
  return EXIT_SUCCESS;
}

Compliant Solution

Do not free In this compliant solution, the memory until it is no longer required.is freed after its final use:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *argv[]) {
  char *buff;
return_val = 0;
  const size_t bufsize = strlen(argv[0]) + 1;
  buffchar *buf = (char *)malloc(BUFSIZEbufsize);
  if (!buffbuf) {
    return EXIT_FAILURE;
  }
  /* handle error condition... */
  strcpy(buf, argv[0]);
  /* ... */
  free(buf);
  return EXIT_SUCCESS;
}

Noncompliant Code Example

In this noncompliant example, realloc() may free c_str1 when it returns a null pointer, resulting in c_str1 being freed twice.  The C Standards Committee's proposed response to Defect Report #400 makes it implementation-defined whether or not the old object is deallocated when size is zero and memory for the new object is not allocated. The current implementation of realloc() in the GNU C Library and Microsoft Visual Studio's Runtime Library will free c_str1 and return a null pointer for zero byte allocations.  Freeing a pointer twice can result in a potentially exploitable vulnerability commonly referred to as a double-free vulnerability [Seacord 2013b].

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
 
void f(char *c_str1, size_t size) {
  char *c_str2 = (char *)realloc(c_str1, size);
  if (c_str2 == NULL) {
    free(c_str1);
  }
}

Compliant Solution

This compliant solution does not pass a size argument of zero to the realloc() function, eliminating the possibility of c_str1 being freed twice:

Code Block
bgColor#ccccff
langc
#include <stdlib.h>
 
void f(char *c_str1, size_t size) {
  if (size != 0) {
    char *c_str2 = (char *)realloc(c_str1, size); 
    if (c_str2 == NULL) {
      free(c_str1); 
    }
  }
  else {
    free(c_str1);
  }
 
}

If the intent of calling f() is to reduce the size of the object, then doing nothing when the size is zero would be unexpected; instead, this compliant solution frees the object.

Noncompliant Code Example

In this noncompliant example (CVE-2009-1364) from libwmf version 0.2.8.4, the return value of gdRealloc (a simple wrapper around realloc() that reallocates space pointed to by im->clip->list) is set to more. However, the value of im->clip->list is used directly afterwards in the code, and the C Standard specifies that if realloc() moves the area pointed to, then the original block is freed. An attacker can then execute arbitrary code by forcing a reallocation (with a sufficient im->clip->count) and accessing freed memory [xorl 2009].

Code Block
bgColor#FFCCCC
langc
void gdClipSetAdd(gdImagePtr im, gdClipRectanglePtr rect) {
  gdClipRectanglePtr more;
  if (im->clip == 0) {
   /* ... */
  }
  if (im->clip->count == im->clip->max) {
    more = gdRealloc (im->clip->list,(im->clip->max + 8) *
                      sizeof (gdClipRectangle));
    /*
     * If the realloc fails, then we have not lost the
     * im->clip->list value.
     */
    if (more == 0) return; 
    im->clip->max += 8;
  }
  im->clip->list[im->clip->count] = *rect;
  im->clip->count++;

}

Compliant Solution

This compliant solution simply reassigns im->clip->list to the value of more after the call to realloc():

Code Block
bgColor#ccccff
langc
void gdClipSetAdd(gdImagePtr im, gdClipRectanglePtr rect) {
  gdClipRectanglePtr more;
  if (im->clip == 0) {
    
  strncpy(buff, argv[1], BUFSIZE-1);
  /* ... */
  }
  if (im->clip->count == im->clip->max) {
    more = gdRealloc (im->clip->list,(im->clip->max + 8) *
                      sizeof (gdClipRectangle));
   free(buff) if (more == 0) return;
  buff   im->clip->max += NULL8;
    im->clip->list = more;
  }
  im->clip->list[im->clip->count] = *rect;
  im->clip->count++;

}

Risk Assessment

Reading memory that has already been freed can lead to abnormal program termination and denial-of-service attacks. Writing memory that has already been freed can additionally lead to the execution of arbitrary code with the permissions of the vulnerable process. 

Freeing memory multiple times has similar consequences to accessing memory after it is freed. Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and might be a trap representation. When reading from or writing to freed memory does not cause a trap, it may corrupt the underlying data structures that manage the heap in a manner that can be exploited to execute arbitrary code. Alternatively, writing to memory after it has been freed might modify memory that has been reallocated.

Programmers should be wary when freeing memory in a loop or conditional statement; if coded incorrectly, these constructs can lead to double-free vulnerabilities. It is also a common error to misuse the realloc() function in a manner that results in double-free vulnerabilities. (See MEM04-C. Beware of zero-length allocations.)

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM30-C

3 (high)

3 (likely)

2 (medium)

High

Likely

Medium

P18

L1

Automated Detection

The LDRA tool suite V 7.6.0 is able to detect violations of this rule.

Fortify SCA Version 5.0 is able to detect violations of this rule.

The tool Compass Rose can detect violations of the rule, except for cases such as the for loop in the first example.

Related Vulnerabilities

Tool

Version

Checker

Description

Astrée
Include Page
Astrée_V
Astrée_V
dangling_pointer_use

Supported

Astrée reports all accesses to freed allocated memory.

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC-MEM30Detects memory accesses after its deallocation and double memory deallocations
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

ALLOC.UAF

Use after free
Compass/ROSE




Coverity

Include Page
Coverity_V
Coverity_V

USE_AFTER_FREE

Can detect the specific instances where memory is deallocated more than once or read/written to the target of a freed pointer

Cppcheck

Include Page
Cppcheck_V
Cppcheck_V

doubleFree
deallocret
deallocuse
Partially implemented
Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

doubleFree
deallocret
deallocuse
Partially  implemented
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF4866, DF4867, DF4868, DF4871, DF4872, DF4873

C++3339, C++4303, C++4304


Klocwork
Include Page
Klocwork_V
Klocwork_V
UFM.DEREF.MIGHT
UFM.DEREF.MUST
UFM.FFM.MIGHT
UFM.FFM.MUST
UFM.RETURN.MIGHT
UFM.RETURN.MUST
UFM.USE.MIGHT
UFM.USE.MUST


LDRA tool suite
Include Page
LDRA_V
LDRA_V

51 D, 484 S, 112 D

Partially implemented

Parasoft C/C++test
Include Page
Parasoft_V
Parasoft_V

CERT_C-MEM30-a

Do not use resources that have been freed
Parasoft Insure++

Runtime analysis
PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

449, 2434

Fully supported

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule MEM30-C

Checks for:

  • Accessing previously freed pointer
  • Freeing previously freed pointer

Rule partially covered.

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V586, V774
Splint
Include Page
Splint_V
Splint_V



TrustInSoft Analyzer

Include Page
TrustInSoft Analyzer_V
TrustInSoft Analyzer_V

dangling_pointer

Exhaustively verified (see one compliant and one non-compliant example).

Related Vulnerabilities

VU#623332 describes a double-free vulnerability in the MIT Kerberos 5 function krb5_recvauth()

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT C Secure Coding StandardMEM01-C. Store a new value in pointers immediately after free()Prior to 2018-01-12: CERT: Unspecified Relationship
CERT CMEM50-CPP. Do not access freed memoryPrior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TR 24772:2013Dangling References

...

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3.2, "The free function"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "DCM Dangling references to stack frames" and "XYK Dangling Reference to Heap"
\[[Kernighan 88|AA. C References#Kernighan 88]\] Section 7.8.5, "Storage Management"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 17.6
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 416|http://cwe.mitre.org/data/definitions/416.html], "Use After Free"
\[[OWASP Freed Memory|AA. C References#OWASP Freed Memory]\]
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management"
\[[Viega 05|AA. C References#Viega 05]\] Section 5.2.19, "Using freed memory"

to Stack Frames [DCM]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TR 24772:2013Dangling Reference to Heap [XYK]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961Accessing freed memory [accfree]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961Freeing memory multiple times [dblfree]Prior to 2018-01-12: CERT: Unspecified Relationship
MISRA C:2012Rule 18.6 (required)Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-416, Use After Free2017-07-07: CERT: Exact
CWE 2.11CWE-6722017-07-07: CERT: Rule subset of CWE

CERT-CWE Mapping Notes

Key here for mapping notes

CWE-672 and MEM30-C

Intersection( MEM30-C, FIO46-C) = Ø CWE-672 = Union( MEM30-C, list) where list =


  • Use of a resource, other than memory after it has been released (eg: reusing a closed file, or expired mutex)


CWE-666 and MEM30-C

Intersection( MEM30-C, FIO46-C) = Ø

CWE-672 = Subset( CWE-666)

CWE-758 and MEM30-C

CWE-758 = Union( MEM30-C, list) where list =


  • Undefined behavior that is not covered by use-after-free errors


CWE-415 and MEM30-C

MEM30-C = Union( CWE-456, list) where list =


  • Dereference of a pointer after freeing it (besides passing it to free() a second time)


Bibliography

[ISO/IEC 9899:2024]7.24.3, "Memory Management Functions"
[Kernighan 1988]Section 7.8.5, "Storage Management"
[OWASP Freed Memory]
[MIT 2005]
[Seacord 2013b]Chapter 4, "Dynamic Memory Management"
[Viega 2005]Section 5.2.19, "Using Freed Memory"
[VU#623332]
[xorl 2009]CVE-2009-1364: LibWMF Pointer Use after free()


...

Image Added Image Added Image AddedMEM09-A. Do not assume memory allocation routines initialize memory      08. Memory Management (MEM)       MEM31-C. Free dynamically allocated memory exactly once