One obvious technique to reduce vulnerabilities in C and C++ programs is to set the pointer to null after the call to free() has completed.
Dynamic memory management
C, UNIX, Win32
Attacker executes arbitrary code on machine with permissions of compromised process or changes the behavior of the program.
Standard C dynamic memory management functions such as malloc() , calloc() , realloc(), and free() [ISO/IEC 99] are prone to programmer mistakes that can lead to vulnerabilities resulting from buffer overflow in the heap, writing to already freed memory, and freeing the same memory multiple times (e.g., double-free vulnerabilities).
One obvious technique to reduce vulnerabilities in C and C++ programs is to set the pointer to null after the call to free() has completed. Dangling pointers (pointers to already freed memory) can result in writing to freed memory and double-free vulnerabilities. Any attempt to dereference the pointer will result in a fault, which increases the likelihood that the error will be detected during implementation and test. Also, if the pointer is set to null, the memory can be freed multiple times without consequence.
While setting the pointer to null should significantly reduce vulnerabilities resulting from writing to freed memory and double-free vulnerabilities, it cannot prevent them when multiple pointers all reference the same data structure. Unfortunately, memory management in C and C++ must be performed with great care.
ISO/IEC. ISO/IEC 9899 Second edition 1999-12-01 Programming languages — C. International Organization for Standardization, 1999.
This material is excerpted from Secure Coding in C and C++, by Robert C. Seacord, copyright © 2006 by Pearson Education, Inc., published as a CERT® book in the SEI Series in Software Engineering. All rights reserved. It is reprinted with permission and may not be further reproduced or distributed without the prior written consent of Pearson Education, Inc.