A simple, yet effective way to avoid double-free and access-freed-memory vulnerabilities is to set pointers to NULL after they have been freed. Calling free() on a NULL pointer results in no action being taken by free(). As a result, it is recommended that freed pointers be set to NULL to help eliminate memory related vulnerabilities.
Non-compliant Code Example 1
may result in accessing freed memory
if (message_type == value_1) {
/* Process message type 1 */
free(message);
}
if (message_type == value_2) {
/* Process message type 2 */
free(message);
}
Non-compliant Code Example 1
memory set to NULL to correct this
if (message_type == value_1) {
/* Process message type 1 */
free(message);
message = NULL;
}
if (message_type == value_2) {
/* Process message type 2 */
free(message);
}
References
- ISO/IEC 9899-1999 Section 7.20.3.2 The free function
- Seacord 05 Chapter 4 Dynamic Memory Management