Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Replaced occurrences of BUFSIZ with BUFFERSIZE to remove ambiguity

...

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#FFCCCC

for (p = head; p != NULL; p = p->next)
    free(p);

...

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

Code Block
bgColor#ccccff

for (p = head; p != NULL; p = q) {
  q = p->next;
  free(p);
}
head = NULL;

...

In this noncompliant code example, buff is written to after it has been freed. These vulnerabilities can be 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(BUFSIZBUFFERSIZE);
  if (!buff) {
     /* Handle error condition */
  }
  /* ... */
  free(buff);
  /* ... */
  strncpy(buff, argv[1], BUFSIZBUFFERSIZE-1);
}

Compliant Solution

In this compliant solution do not free the memory until it is no longer required.

Code Block
bgColor#ccccff

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

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

...