dynamic memory
Most modern languages support dynamic memory allocation.
When it is needed, call a special function to ask for a chunk of memory of the required size. The system makes finds an appropriately-sized chunk, and returns a pointer to it. The chunk can then be used as an array or whatever.
The pool of memory where such chunks live is called the heap. It is managed by the operating system.
By contrast, variables declared in routine bodies is said to live on the stack. The stack grows as the program enters into routines, and shrinks as it exits them.
example: linked list
reasons for
-
run-time determination of memory requirement
otherwise, program must be written to know at at compile time how much memory is needed for each task.
-
memory that persists independently of the procedure-call structure
natural for many applications
-
stack size limitations
to use a really big chunk of memory, one must allocate it
dangers
-
allocation fails
need to recover gracefully
-
fail to free allocated memory
called a memory leak
other considerations
- memory allocation by the system takes some time
- more memory is usually allocated than actually requested
These are very system-dependent, and usually unproblematic. However, if doing millions of allocations, consider doing a custom memory allocation.