🔴 Advanced · Lesson 33
Dynamic Memory (malloc/free)
Dynamic Memory
Dynamic Memory
Dynamic memory allocation means memory is allocated at run time from the heap. It is useful when the required size is not known before program execution.
| Function | Use |
|---|---|
malloc() | Allocates uninitialized memory |
calloc() | Allocates zero-initialized memory |
realloc() | Changes size of allocated memory |
free() | Releases allocated memory |
malloc Example
C Language
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter number of students: ");
scanf("%d", &n);
int *marks = (int*) malloc(n * sizeof(int));
if(marks == NULL) {
printf("Memory allocation failed");
return 1;
}
for(int i = 0; i < n; i++)
scanf("%d", &marks[i]);
for(int i = 0; i < n; i++)
printf("%d ", marks[i]);
free(marks);
return 0;
}calloc Example
C Language
int *arr = (int*) calloc(5, sizeof(int));
for(int i = 0; i < 5; i++)
printf("%d ", arr[i]); // all values are 0
free(arr);realloc Example
C Language
int *arr = (int*) malloc(3 * sizeof(int)); arr = (int*) realloc(arr, 5 * sizeof(int));
free and Common Mistakes
⚠️ Common Mistakes
- Forgetting
free()causes memory leak - Using pointer after
free()is dangling pointer problem - Always check
NULLafter allocation
Summary
- Use dynamic memory when size is known at run time
mallocgives uninitialized memorycallocinitializes memory to zeroreallocchanges allocated block size- Always release heap memory using
free
Dynamic Memory
Dynamic memory allocation में memory run time पर heap से allocate होती है। जब size पहले से पता न हो, तब यह बहुत useful होती है।
| Function | Use |
|---|---|
malloc() | Uninitialized memory allocate करता है |
calloc() | Zero-initialized memory allocate करता है |
realloc() | Memory size बदलता है |
free() | Memory release करता है |
malloc
C Language
int *marks = (int*) malloc(n * sizeof(int));
if(marks == NULL) {
printf("Memory failed");
return 1;
}calloc
C Language
int *arr = (int*) calloc(5, sizeof(int)); // सभी values 0 होंगी free(arr);
realloc
C Language
arr = (int*) realloc(arr, newSize * sizeof(int));
free और Mistakes
⚠️ सावधानी
free()न करने से memory leak होता हैfree()के बाद pointer use न करें- Allocation के बाद
NULLcheck करें
सारांश
- Run time size के लिए dynamic memory use करें
- malloc uninitialized memory देता है
- calloc zero-initialized memory देता है
- realloc size change करता है
- free memory release करता है