In this video, we're going to step through the following code,
which repeatedly mallocs an array inside of a for loop.
In the first version,
we're not going to free that array causing a memory leak,
but in the second version we are going to use free.
Let's see how both versions play out.
We begin inside of main and initialize a variable X and step into a for loop where I,
initially has the value 10.
The first line in the for loop is going to malloc space on the heap for 10 integers,
and P will point to that location on the heap.
Let's assume we have a function,
do some computation that will initialize that array and perform some kind of computation,
such that the value of X will change.
Keep in mind that at the end of this iteration of the
for loop the variable P will no longer exist.
So when we return to the beginning of the for loop, P goes away.
What this also means is that,
we've lost our pointer to the memory that we allocated on the heap.
This memory is now leaked.
There's no way to access it,
there's no way to free it.
We've incremented I to 11 and we're going to execute another iteration of the for loop.
This time we're going to malloc space for 11 integers.
Now notice what's going to happen in every single iteration of the loop.
We're going to allocate memory and then leak it a larger and larger amount each time.
This is not what we want.
Let's consider instead, a version of this code where we
have included a statement to free the memory that we allocate on the heap.
Once again we begin in main,
we initialize a variable X to zero
and enter the for loop where I initially has the value 10.
We malloc space for 10 integers,
then perform this computation which initializes the array and changes the value of X.
Finally, before we leave this iteration of our for loop,
we're going to free the memory pointed to by P. Now,
when the variable P disappears we haven't leaked any memory.
I has been incremented to 11.
We go back into the for loop,
we're going to malloc space for 11 integers.
Once again, we call this computation function which initializes the array and changes X.
And once again, we free the memory pointed to by P. Now,
we could do another iteration of the for loop.
Notice that every time we allocate memory we free it.
So we're not amassing more and more leaked memory in the heap,
as we did in the first example.