Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider v2.4 (sch jbop) (X_X)@==(Q_Q)@

...

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
This 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.

...

Code Block
bgColor#ccccff
for (p = head; p != NULL; p = q) {
  q = p->next;
  free(p);
}
head = NULL;

...

Noncompliant Code Example

In this 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 const *argv[]) {
  char *buff;

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

...

Code Block
bgColor#ccccff
int main(int argc, const char const *argv[]) {
  char *buff;

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

...