The free store Vs Memory Leaks
Acording to my book there are 5 areas of memory available to a C++ program:
Global name space, The free store, Registers, Code space, The stack.
Global namespace is used for global variables, The stack is used for local variables in functions, Code space is to store the program code, and Registers of cource do the obvious.
So this leaves the free store. This is what confuses me:
Acording to my book:
Quote:
The problem with local variables is that they don't persist: when a function returns, the local variables are thown away
Thats understandable and the way it should be..
Quote:
The advantage to the free store is that the memory you reserve remains available untill you explicitly free it...If you reserve memory on the free store while in a function, the memory is still available when the function returns
Great..
Quote:
The advantage of accessing memory this way, rather then useing global variables, is that only functions with access to the pointer have access to the data.
And this is very understandable but then....
Quote:
Remember that the pointer itself--as oposed to the memory to which it points--is a local variable. When the function in which it is declared returns, that pointer goes out of scope and is lost
Acording to them if I forget to free the memory before the function returns I will have a memory leak, which is understandble, since the memory was not freed and the pointer to it was lost, you may no longer access that memory and it takes up space, thus less memory available for other data.
Here is the part I don't understand:
I dont understand that if the pointer is lost at the end of a function, then why is it a advantage that the free store remains available after the function returns when we no longer have a pointer to it.
What I mean is origionaly it was quoted that "the memory is still available when the function returns" which since the pointer itself was a local variable and was lost, and now we dont have access to that data that was in the free store, although it is still there, we no longer have a handle for it and may not access it, thus whatever I stored there is invisible now....
Can someone explain why they are contradicting themself??