The following is an assignment statement in the current version of
analyze_trades
:
trade_pointers[limit] = (struct trade*) malloc (sizeof (struct trade));
To prevent the memory leak, you use
the free
function before you
reassign a pointer and lose your access to the memory you want to reclaim.
You can, for example, deploy the
free
function just before
the allocation of new objects:
... free (trade_pointers[limit]); trade_pointers[limit] = (struct trade*) malloc (sizeof (struct trade)); ...
So situated, the free
function reclaims memory previously allocated
by the corresponding malloc
. Once reclaimed, memory automatically
becomes available for subsequent applications of malloc
.
The first time that analyze_trades
is called, the
trade_pointers
array contains pointers to 0, because the elements of
global arrays are initialized to 0 by the C compiler. Fortunately,
free
does nothing when its argument is 0.