Versions Compared

Key

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

Accessing memory once it is freed may corrupt the data structures used to manage the heap. References to memory that has been deallocated are referred to as dangling pointers. Accessing a dangling pointer can lead to security result in exploitable 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 data at the freed location may appear valid. However, this can change unexpectedly, leading to unintended program behavior. As a result, it is necessary to guarantee that memory is not written to or read from once it is freed.

Noncompliant Code Example

Wiki Markup
ThisIn this noncompliant code example from Kernighan and Ritchie \[[Kernighan 88|AA. C References#Kernighan 88]\] 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.

...

Noncompliant Code Example

In this noncompliant code example, buff is written to after it has been freed. These 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
int main(int argc, const char *argv[]) {
  char *buff;

  buff = (char *)malloc(BUFSIZ);
  if (!buff) {
     /* handleHandle error condition */
  }
  /* ... */
  free(buff);
  /* ... */
  strncpy(buff, argv[1], BUFSIZ-1);
}

...