Dynamic Memory Allocation in C
Definition:
Dynamic memory allocation allows memory to be allocated during runtime using pointers.
🔹 Functions used (in stdlib.h):
|
Function |
Description |
|
malloc() |
Allocates memory block |
|
calloc() |
Allocates memory and initializes it to 0 |
|
realloc() |
Re-allocates memory block |
|
free() |
Frees allocated memory |
Example – Using malloc():
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
ptr = (int *)malloc(3 * sizeof(int));
if (ptr == NULL) {
printf(“Memory not allocated\n”);
return 1;
}
ptr[0] = 10;
ptr[1] = 20;
ptr[2] = 30;
for (int i = 0; i < 3; i++) {
printf(“%d “, ptr[i]);
}
free(ptr); // release memory
return 0;
}