Versions Compared

Key

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

...

Alternatively, a pointer may be set to point to another valid object.

Non-Compliant Code Example

In this example, the type of a message is used to determine how to process the message itself. It is assumed that message_type is an integer and message is a pointer to an array of characters that were allocated dynamically. If message_type equals value_1, the message is processed accordingly. A similar operation occurs when message_type equals value_2. However, if message_type == value_1 evaluates to true and message_type == value_2 also evaluates to true, then message will be freed twice, resulting in an error.

Code Block
bgColor#FFcccc
if (message_type == value_1) {
  /* Process message type 1 */
  free(message);
}
/* ...*/
if (message_type == value_2) {
   /* Process message type 2 */
  free(message);
}

Compliant Solution

As stated above, calling free() on a null pointer results in no action being taken by free(). By setting message equal to NULL after it has been freed, the double-free vulnerability has been eliminated.

Code Block
bgColor#ccccff
if (message_type == value_1) {
  /* Process message type 1 */
  free(message);
  message = NULL;
}
/* ...*/
if (message_type == value_2) {
  /* Process message type 2 */
  free(message);
  message = NULL;
}

Risk Assessment

Setting pointers to NULL after memory has been freed is a simple and easily implemented solution for reducing dangling pointers. Dangling pointers can result in freeing memory multiple times or in writing to memory that has already been freed. Both of these problems can lead to an attacker executing arbitrary code with the permissions of the vulnerable process.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MEM01-A

3 (high)

2 (probable)

3 (low)

P18

L1

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3.2, "The free function"
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management"
\[[Plakosh 05|AA. C References#Plakosh 05]\]

...