One of the main challenges of heap management is to prevent memory leaks. A memory leak is when a block of memory is allocated and the pointer to it is lost so that it cannot be released until the program quits. The following is a simple example of a memory leak:
Card* pCard = (Card*)calloc( 1 , sizeof( Card );
...
pCard = (Card*)calloc( 1 , sizeof( Card ); // <-- Leak!
In this example, pCard first points to one block of heap memory and then is later assigned to another. The first block of memory is allocated but, without a pointer to it, it cannot be freed. To correct this error, call free() before reassigning pCard.
A more subtle leak is as follows:
struct Thing1 {
int size;
struct Thing2* pThing2
}
struct Thing1* pThing1 = (struct Thing1*)calloc( 1 , sizeof(Thing1) );
Thing1->pThing2 = (struct Thing2*)calloc( 1 , sizeof(Thing2) );
...
free( pThing1 ); // <-- Leak!
In this example, we create theThing1 structure, which...