OK, let's take a little time to explore what is really the issue here.
First off, as others have pointed out, it is good practice to set a pointer variable, in your case
value
to NULL when you "free up" some allocated memory, using either
free()
or
delete
as appropriate. In other languages (like C#) the variable would be more properly called the "referencer" but in C/C++ it is the "pointer" variable.
However, as others have pointed out, you have really created a second copy of the "pointer" when you added
value
to the
vector
, so now you have two variables, each pointing to the same memory location. There is no magic on this planet that will run around and look at all the variables you have and set them to NULL if they point to some block of memory being "freed up". You have to do that yourself.
Now you do, in fact, follow this good practice when you use
delete
on the
list[i]
element and immediately set the pointer to NULL. So you are on the right track.
This brings up the issue of "ownership". Usually, having multiple pointers to the same allocated memory block is a bad idea. Oh, I can see times when that's useful but it has confused you in this usage. Once you added the value of
value
to the vector, you "gave up ownership" of that allocated memory to the vector. A fact that you recognize because you are doing the actual "freeing up" of that memory by referencing it through
list
.
What is another good practice is to also NULL out a pointer when you yield "ownership" to another variable / place. In this instance, if you really did not want a lingering pointer to the memory left in
value
, you should set it to NULL after adding it to the vector. In other words, once you added it to vector,
value
no longer "owns" what happens to that memory and at that point, to avoid future problems, you should have set the contents to NULL.
list.push_back(value);
value = NULL;
This "giving up of ownership" is demonstrated quite nicely in the earlier part of your code where you use a single pointer,
a
inside a loop to allocate 10 different memory blocks. Clearly each time through the loop you overwrite (some would say "clobber")
a
with the next allocation but, fortunately for you, you created another copy of the pointer by placing it in the vector.