Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor edits; reviewed

...

Reading a pointer to deallocated memory is undefined behavior because the pointer value is indeterminate and can have  and might be a trap representation. In the latter case, doing so may cause Fetching a trap representation might perform a hardware trap (but is not required to).

When memory is freed, its contents may might remain intact and accessible because it is at the memory manager's discretion when to reallocate or recycle the freed chunk. The data at the freed location may can appear valid. However, this can change unexpectedly, leading to unexpected program behavior. As a result, it is necessary to guarantee that memory is not written to or read from once it is freed.

...

This example from Brian Kernighan and Dennis Ritchie [Kernighan 1988] shows both the incorrect and correct techniques for freeing the memory associated with a linked list. In their incorrect their (intentionally) incorrect solution, p is freed before the p->next is executed, so that p->next reads memory that has already been freed.

...

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);
  }
}

...

Freeing memory multiple times has similar consequences to accessing memory after it is freed.  First, reading a pointer to freed deallocated memory is undefined behavior because the pointer value is indeterminate and can have  and might be a trap representation. In the latter case, doing so can cause a hardware trap.   When reading a freed pointer doesn't cause a trap, the underlying data structures that manage the heap can become corrupted in a way manner that can introduce security vulnerabilities into a program. These types of issues are called double-free vulnerabilities. In practice, double-free vulnerabilities can be exploited to execute arbitrary code.  To eliminate These coding errors are referred to as "double-free vulnerabilities".

, it is necessary to guarantee that dynamic memory is freed exactly once. 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

High

Likely

Medium

P18

L1

...