Versions Compared

Key

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

Wiki Markup
Calling {{free()}} on a block of dynamic memory marks that memory for deallocation. Once deallocated, the block of memory is made available for future allocation. However, the data stored in the block of memory to be recycled may be preserved. If this memory block contains sensitive information, that information may be unintentionally exposed. This phenomenon is referred to as _heap inspection_ \[ref\]. To prevent heap inspection it is necessary to clear sensitive information from dynamically allocated buffers before they are freed.

This type of defect can lead to information leakage as is stated in Rule: MEM33-C. Do not assume memory allocation routines initialize memory.

Non-Compliant Code Example 1

In this example, sensitive information in stored in the buffer secret is copied to the dynamically allocated buffer, new_buff, which is then processed and eventually marked for deallocation with free(). However, the contents of new_buff may remain in heap memory after being marked for deallocation. Furthermore, if this memory is recycled by the heap manager, the information stored in new_buff may be exposed to another, unintended section of the program, or another program entirely.

Code Block
bgColor#FFcccc

...
new_buff = malloc(strlen(secret)+1);
if (!new_buff) {
  /* Handle Error */
}
strcpy(new_buff, secret);
/* Process new_buff... */
free(new_buff);
...

Compliant Solution 1

Non-Compliant Code Example 2

Using realloc() to resize dynamic memory may allow heap inspection attacks. realloc() may allocate a new, larger block of memory, copy the contents, of buffer to this new block, free() the original block, and assign the newly allocated block to buffer. However, the contents of the original block may remain in heap memory after being marked for deallocation.

Code Block
bgColor#FFcccc

...
buffer = realloc(buffer,new_size);
...

Compliant Solution 2

Code Block