Memory Map and Free Store 

The memory that a program uses is typically divided into a few different areas:

• Global namespace - contains global variables
• The free store (heap) - contains dynamically allocated variables 
• Registers - are used for internal housekeeping functions, such as keeping track of the stack and the instruction pointer.
• Code space - contains the program.
• The stack - is used for storing function parameters, local variables, and other function-related information.

The Free Store

The free store is a large pool of unallocated memory for dynamic allocation during the program execution.  Objects allocated on the free store are manipulated indirectly through pointers. Free store memory is allocated through the new operator and deallocated through the delete operator.  The advantage of the free store is that reserved memory is available until explicitly released. Memory allocated on the free store while in a function will still be available when the function returns.  The disadvantage of the free store is that the reserved memory remains unavailable until explicitly released. Failure to free this memory can build up over time resulting in a memory leak which can result in performance issues and a possible system crash. 

Allocating Space with the New Keyword

Memory is allocated on the free store by using the new keyword followed by the type of object to be created. This tells the compiler how much memory to set aside.  To request new memory for a variable type int using the following -

int *ptr = NULL;//creates a pointer ptr and assigns NULL
ptr = new int;// allocated space for an int on the heap and assign is address to pointer ptr

or

int *p = new int

Deallocating Space with the Delete Keyword

When an area of the free store is no longer required, it must be released back to the system. This is done by calling delete on the pointer.  If a pointer variable points to the free store memory and the pointer goes out of scope, the memory is not automatically returned to the free store and becomes unavailable. This is called a memory leak. To release memory back to the free store use the keyword delete - 

delete pPointer;

The code section below illustrates the allocating and deleting of a pointer

#include <iostream>
using namespace std;
int main()
{
int * pInt= new int;//create pointer pInt
*pInt=7;//assign value 7
cout << "*pInt: " << *pInt << endl;//output value of pInt
delete pInt;//delete pointer
cout << "*pInt after deleting: " << *pInt << endl;//output pointer value
return 0;
}

If there is insufficient space on the heap the request to allocate memory will fail. The new request will be in the form of an exception of type std::bad_alloc.  If “nothrow” is used with the new operator, it will return a NULL pointer. To add a free store request fail exception to the above code segment -

int *pInt = new(nothrow) int;
if (!pInt)
cout << "allocation of memory failed\n";