Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

...

Noncompliant Code Example (free)

Wiki MarkupThis example from Kernighan and Ritchie \ [[Kernighan 88|AA. Bibliography#Kernighan 88]\] shows both the incorrect and correct techniques for removing items from a linked list. The incorrect solution, clearly marked as wrong in the book, is bad because {{p}} is deallocated before the {{p->next}} is executed, so {{p->next}} reads memory that has already been deallocated.

Code Block
bgColor#FFCCCC
langcpp
for (p = head; p != NULL; p = p->next)
    free(p);

...

This rule appears in the C Secure Coding Standard as MEM30-C. Do not access freed memory.

Bibliography

Wiki Markup\[[Henricson 97|AA. Bibliography#Henricson 97] \] Rule 8.3 Do not access a pointer or reference to a deleted object \
[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999] \] Section 7.20.3.2, "The {{free}} function" \
[[ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772] \] "DCM Dangling references to stack frames" and "XYK Dangling Reference to Heap" \[
[Kernighan 88|AA. Bibliography#Kernighan 88] \] Section 7.8.5, "Storage Management" \
[[MISRA 04|AA. Bibliography#MISRA 04] \] Rule 17.6 \
[[MITRE 07|AA. Bibliography#MITRE 07]\] [CWE ID 416|http://cwe.mitre.org/data/definitions/416.html], "Use After Free" \
[[OWASP Freed Memory|AA. Bibliography#OWASP Freed Memory]\] \
[[Seacord 05a|AA. Bibliography#Seacord 05] \] Chapter 4, "Dynamic Memory Management" \
[[Viega 05|AA. Bibliography#Viega 05] \] Section 5.2.19, "Using freed memory"

...

MEM13-CPP. Use smart pointers instead of raw pointers for resource management      08. Memory Management (MEM)      MEM31-CPP. Free dynamically allocated memory exactly once