There are two problems -
One is memory leak and another is memory corruption which are similar in the nature and we should always use the following topology -
1. Always nullify the pointer after free.
2. While free first check if it is null.
3. Use the smart pointer in C++ to avoid the dangling pointer (http://ootips.org/yonat/4dev/smart-pointers.html )
4. Always check the return of malloc to see if was succeeded
5. You can create a wrapper over malloc and free to to keep the track of count i.e. free count and allocated count on the following lines -
void *my_alloc (size_t size)
p = malloc(size);
void my_free (void *p)
and at the end u can match the free count to the allocated count.