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.
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);
}
|
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);
}
|