![]() |
VOOZH | about |
Memory allocation in C determines how and when memory is assigned to variables and data structures during program execution. Efficient memory management is crucial for building optimized and bug-free programs. In C, memory allocation is categorized into two types:
Before understanding static and dynamic allocation, it’s important to know how memory is organized in a program.
Note: Heap memory cannot be accessed directly; it can only be accessed through pointers.
Static memory allocation means that the memory for variables is allocated at compile-time, before the program starts executing.
1 2 3 4 5
Explanation: Here, the array arr[5] gets memory from the stack during compile-time. The size cannot change while the program runs.
Dynamic memory allocation means that memory is allocated at runtime, i.e., while the program is executing. It allows flexible memory usage based on the program’s needs.
There are some functions available in the stdlib.h header which will help to allocate memory dynamically.
Example: Using malloc() and free()
Examples: Memory for n integers is allocated at runtime using malloc(). ptr points to the allocated memory block in the heap. After use, free(ptr) is called to prevent memory leaks.
Advantages:
Disadvantages:
| Basis | Static Memory Allocation | Dynamic Memory Allocation |
|---|---|---|
| When Allocated | Compile-time | Run-time |
| Memory Area Used | Stack | Heap |
| Flexibility | Fixed size | Can change size at runtime |
| Deallocation | Automatically done | Must be done manually using free() |
| Speed | Faster | Slightly slower due to runtime allocation |
| Example | int arr[10]; | int *arr = malloc(10 * sizeof(int)); |