Refer the Sample Here
Allocating and clearing the
memory in the memory segment for Stack, Code and data is taken care by the
system. But, heap memory is given in the hands of C++ programmer.
They can create byes of memory as well as clear it whenever they want. So the programmer determines the lifetime of
the memory allocated. Consider the statement below taken from the example:
//MemSeg06: Local pointer storing the heap
address and assigning a value to the heap
int
*pInt = new int;
*pInt = 22;
In the above statements, space
required to store an integer value is allocated in the heap. The allocated
address is stored in the variable pInt. The variable pInt is
inside the main function and so the space for variable pInt is allocated in the
stack holding address in the heap (Enough to store an integer). So when we go out of the function all the
stack memory associated to it is cleared. But, the allocated heap becomes un
attended or blocked stating in use. Because system will not clear it and
programmer should do that. To clear that heap, before you lose the address in
the stack for pInt, you should use the statement delete pInt.
What
happens if the above two statements are next to the comment MemSeg01 that
is not inside any of the function? Well. Heap memory is stored in data segment
variable pInt.