How does static allocation differ from dynamic allocation of memory?
Static allocations exist for the entire duration a program is running. The amount of memory required for static variables is fixed size and is determined at compile time. The allocation itself occurs at load time based upon information found in the program's data segment. In simplistic terms, the data segment is part of the executable file itself and is loaded alongside the text segment which contains all the program code. The data segment has several regions to cater for constants, global variables and static variables, divided into initialised and uninitialised data. The program loader uses the information in the data segment to determine the amount of memory to allocate and where to allocate each datum.
Dynamic allocations occur at runtime in a region of memory known as the heap. Normally, a program will request additional memory from the heap via the operating system's memory manager on an as-required basis. However, requesting memory from the operating system has a runtime cost in terms of performance. To alleviate this, programs often provide their own memory manager which will make a one-time request for a chunk of contiguous memory which it can then use as it sees fit, allocating additional chunks as and when required, thus reducing the number of low-level system calls. However, all dynamic allocations must be returned to the system as soon as they are no longer required. This means the program must keep track of every allocation at all times. Failure to keep track of dynamic allocations will result in resource leaks and (ultimately) in running out of memory altogether.
There is also a third region of memory known as the call stack (or simply the stack). Every thread in a process has its own call stack and is used to keep track of functions: return addresses; arguments; local variables and; exception handlers. Each call stack is fixed size (determined at compile time) and is allocated at runtime whenever a thread loads (every process has at least one thread). The call stack usually resides at the top of the virtual address space and grows down into lower addresses.