St at i c Me m o r y A l l o cat i o n:
Allocation: Memory is allocated at compile time, meaning the size of memory is pre-decided
before the program runs.
Storage: Allocated memory is stored in the stack, a memory region with limited size.
Declaration:Variables are declared with a fixed size using keywords like `int`, `char`, `float`, etc.
Example:
int age = 25; // Allocates 4 bytes for an integer variable
char name[20] = "Alice"; // Allocates 20 bytes for a character array
D ynam ic Me m o r y Allo cat io n:
Allocation: Memory is allocated at runtime, meaning the size can be determined during program
execution.
Storage: Allocated memory is stored in the heap, a larger memory region.
Operators: Uses `new` to allocate memory and `delete` to deallocate it.
Example:
int *ptr = new int(10); // Allocates 4 bytes for an integer on the heap
char *str = new char[50]; // Allocates 50 bytes for a character array on the heap
Use the memory...
delete ptr; // Deallocates memory for the integer
delete[] str; // Deallocates memory for the character array
```
K e y D if f e r e nce s :
| Feature | Static Memory Allocation | Dynamic Memory Allocation |
|----------------|--------------------------|---------------------------|
| Allocation time| Compile time | Runtime |
| Storage area | Stack | Heap |
| Size | Fixed | Flexible |
| Allocation | Automatic | Manual (using `new`) |
| Deallocation | Automatic | Manual (using `delete`) |
W h e n t o U s e W h i ch :
* Use static memory allocation when you know the size of data beforehand and it won't change
during execution.
* Use dynamic memory allocation when you need flexibility in memory size or when the size is
unknown until runtime.
I m po r t an t C o n s i d e r at i o ns :
Memory Leaks:Be cautious with dynamic allocation to avoid memory leaks, which occur when
memory is allocated but not properly deallocated.
Performance: Static allocation is generally faster than dynamic allocation due to less overhead.