The stack is limited in space and is not designed to store large amounts of data. So for any major data structure of file we need to store it somewhere else in memory. Programming languages obviously have to ask the memory manager for extra memory. They call this extra memory the heap.

When memory is allocated a space on the heap is created. A pointer or reference to that memory is then passed back so the programmer can then do what they need with the memory. It is important to remember that data must first be allocated off the heap before it can be used. This is because the memory manager must first allow the program to use the memory.

The diagram shows what the heap may look like. The heap is memory and is simply stored somewhere in memory. Although we think of the heap as a continuous blob of memory it is in fact split across numerous pages.

When memory allocation occurs extra space is allocated onto the heap. This is done in many ways. Allocation needs only one piece of information and that is how much memory will it need. It then returns a reference to that memory so the language can access it. Access to the heap is always done via pointers. Some languages try and hide pointers and use the ideas of references. However remember that they will use pointers internally and are simply abstracting this detail away from the programmer.

De-allocation of memory is crucial. As programs using the heap will more than likely be using a lot of memory it is important that the relinquish memory as soon as it can. If memory is not released there could be scenarios where memory runs out. This is especially important if the software will be running for a long time. De-allocation can occur in two ways, direct or through garbage collection,

Direct de-allocation is simple. It simply releases the memory from the heap using the pointer it already had to the data. The problem with direct de-allocation is that you have to rely on the programmer to specifically do it. A lot of programmers are not very good at dislocating memory. As such we get the term memory leaks. A memory leak is where you have memory which is no longer used but still allocated for a task by a program. Direct is normally only used when pointers are used. Languages which use references tend to use garbage collection.