Static and Dynamic Memory Allocation in C (original) (raw)

Last Updated : 6 Nov, 2025

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:

memory_allocation

memory-allocation

How a Program Uses Memory

Before understanding static and dynamic allocation, it’s important to know how memory is organized in a program.

code_section

**Note: Heap memory cannot be accessed directly; it can only be accessed through pointers.

1. Static Memory Allocation

Static memory allocation means that the memory for variables is allocated at compile-time, before the program starts executing.

#include <stdio.h>

int main(){

// memory allocated statically
int arr[5];  
for (int i = 0; i < 5; i++) {
    arr[i] = i + 1;
    printf("%d ", arr[i]);
}
return 0;

}

`

**Explanation: Here, the array arr[5] gets memory from the stack during compile-time. The size cannot change while the program runs.

Advantages

Disadvantage

Dynamic memory allocation

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.

Common Functions For Allocate Memory Dynamically.

There are some functions available in the stdlib.h header which will help to allocate memory dynamically.

**Example: Using malloc() and free()

C `

#include <stdio.h> #include <stdlib.h>

int main(){

int *ptr;
int n, i;

printf("Enter number of elements: ");
scanf("%d", &n);

 // memory allocated dynamically
ptr = (int*) malloc(n * sizeof(int));

if (ptr == NULL) {
    printf("Memory not allocated.\n");
    return 1;
}

for (i = 0; i < n; i++) {
    ptr[i] = i + 1;
}

printf("Array elements: ");
for (i = 0; i < n; i++) {
    printf("%d ", ptr[i]);
}

// releasing memory
free(ptr);
return 0;

}

`

**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:

Static vs Dynamic Memory Allocation

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));