Static and Dynamic Memory Allocation
Memory allocation is a crucial concept in computer programming, determining how
memory is allocated, managed, and deallocated. There are two primary types of
memory allocation: static and dynamic.
Static Memory Allocation
Definition: Static memory allocation is the process of allocating memory at compile
time before the associated program is executed. Once allocated, the memory size is
fixed and cannot be changed during runtime.
Characteristics
1. Fixed Size: The size of the memory allocated is fixed and known at compile
time.
2. Efficient Access: Access to static memory is generally faster because the
memory addresses are resolved at compile time.
3. Scope and Lifetime: The allocated memory exists throughout the lifetime of
the program and is automatically deallocated when the program terminates.
4. No Fragmentation: Since the memory is allocated and deallocated at compile
time, there is no runtime fragmentation.
Examples in C/C++
● Global Variables: Declared outside any function, accessible throughout the
program.
● Static Variables: Declared with the static keyword, retaining their value
between function calls.
Dynamic Memory Allocation
Definition: Dynamic memory allocation is the process of allocating memory during
runtime as needed. The size of the memory block can be modified, and the memory
can be allocated or deallocated as required.
Characteristics
1. Flexible Size: The size of the memory can be determined and modified at
runtime, allowing for flexible data structures.
2. Heap Allocation: Memory is allocated from the heap, a pool of memory
reserved for dynamic allocation.
3. Manual Management: The programmer must explicitly manage the allocation
and deallocation of memory, which can lead to memory leaks if not handled
properly.
4. Fragmentation: Over time, dynamic memory allocation can lead to
fragmentation, causing inefficient use of memory.
Functions for Dynamic Memory Allocation
● C/C++: malloc, calloc, realloc, free (C), and new, delete (C++).
Comparison Between Static and Dynamic Memory Allocation
Aspect Static Memory Allocation Dynamic Memory
Allocation
Timing Compile-time Runtime
Flexibility Fixed size Flexible size
Memory Area Stack and data segment Heap
Speed Faster access Slower access due to heap
management
Management Automatic Manual (explicit allocation
and deallocation)
Fragmentation No fragmentation Possible fragmentation
Lifetime Entire program duration Controlled by programmer
(variable)
Examples Global variables, static Dynamic arrays, linked lists,
variables dynamic objects