Versions Compared

Key

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

...

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

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

Non-Compliant Code Example

The new and delete operators permit the same kind of behavior.

Code Block
bgColor#FFcccc

int num = 5;
SomeClass *sc = new SomeClass[num];
// ...
delete [] sc;
// ...
SomeClass& ref = sc[0]; // undefined behavior!

Compliant Solution delete[]

Code Block
bgColor#ccccff

int num = 5;
SomeClass *sc = new SomeClass[num];
// ...
delete [] sc;
sc = 0;
// ...
if (sc==0) ... // now safe

Risk Assessment

Reading memory that has already been freed can lead to abnormal program termination and denial-of-service attacks. Writing memory that has already been freed can lead to the execution of arbitrary code with the permissions of the vulnerable process.

...

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

References

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

...