Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Do no evaluate any pointers into freed memory after an allocated block of dynamic storage has been deallocated by a memory management function, including dereferencing or acting as an operand of an arithmetic operation, type casting, or using the pointer as the right-hand side of an assignment.

According to the C standard [ISO/IEC 9899:2011]C Standard, the behavior of a program that uses the value of a pointer that refers to space deallocated by a call to the free() or realloc() function is undefined. (See undefined behavior 177  of Annex J.)

...

Noncompliant Code Example

This example from Brian Kernighan and Dennis Ritchie [Kernighan 1988] shows 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 freed.

...

In this noncompliant example (CVE-2009-1364) from libwmf version 0.2.8.4, the return value of gdRealloc (a simple wrapper around realloc which 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 ISO/IEC 9899:2011 the C Standard specifies that if realloc moves the area pointed to, then the original 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].

...

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

Related Guidelines

...

...

TR 24772:2013Dangling References to Stack Frames [DCM]
Dangling Reference to Heap [XYK]
ISO/IEC TS 17961 (Draft)Accessing freed memory [accfree]

ISO/IEC TR 24772 "DCM Dangling references to stack frames" and "XYK Dangling reference to heap"

...

...

...

Use after free

...

Bibliography

[Kernighan 1988]Section 7.8.5, "Storage

...

Management"
[OWASP Freed Memory] 
[Seacord 2005a]Chapter 4, "Dynamic Memory Management"
[Viega 2005]Section 5.2.19, "Using

...

...