Dangling pointers can lead to exploitable double-free and access-freed-memory vulnerabilities. A simple yet effective way to eliminate dangling pointers and avoid many memory-related vulnerabilities is to set pointers to NULL after they have been freed, or set them to another valid object.
Calling free() on a null pointer results in no action being taken by free().
Noncompliant Code Example
...
| Code Block | ||
|---|---|---|
| ||
char *message; int message_type; /* initializeInitialize message and message_type */ if (message_type == value_1) { /* Process message type 1 */ free(message); } /* ...*/ if (message_type == value_2) { /* Process message type 2 */ free(message); } |
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 is freed twice, resulting in an error.
Compliant Solution
As stated above, calling Calling free() on a null pointer results in no action being taken by free(). Setting message to NULL after it has been freed eliminates the possibility that the message pointer can be used to free the same memory more than once.
...