📘 Lesson · Lesson 57
Dynamic Memory (malloc/free)
Dynamic Memory (malloc/free)
What is Dynamic Memory?
💡 Note
Dynamic memory is memory allocated at run-time from the heap using malloc/calloc, resized with realloc, and released with free.
The Functions
| Function | Use |
|---|---|
| malloc(n) | allocate n bytes (uninitialized) |
| calloc(n,size) | allocate and set to zero |
| realloc(p,n) | resize an existing block |
| free(p) | release the memory |
Example
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*) malloc(3 * sizeof(int));
arr[0]=10; arr[1]=20; arr[2]=30;
printf("%d\n", arr[1]); // 20
free(arr); // always free!
return 0;
}Output:
20
20
Summary
- malloc/calloc allocate heap memory; realloc resizes; free releases it.
- Always free to avoid memory leaks.
Dynamic Memory क्या है?
💡 Note
Dynamic memory run-time पर heap से malloc/calloc से allocate होती है, realloc से resize, और free से release।
Functions
| Function | Use |
|---|---|
| malloc(n) | n bytes allocate (uninitialized) |
| calloc(n,size) | allocate और zero set |
| realloc(p,n) | मौजूदा block resize |
| free(p) | memory release |
Example
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*) malloc(3 * sizeof(int));
arr[0]=10; arr[1]=20; arr[2]=30;
printf("%d\n", arr[1]); // 20
free(arr); // हमेशा free करें!
return 0;
}Output:
20
20
सारांश
- malloc/calloc heap memory allocate; realloc resize; free release करता है।
- Memory leaks से बचने को हमेशा free करें।