Dynamic Memory Allocation
Dynamic Memory Allocation
Example:
int *ptr;
ptr = (int *)malloc(5 * sizeof(int));
Example:
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
3. realloc() - Re-Allocation
Syntax:
Example:
free(ptr);
Example:
free(ptr);
Important Points:
Always check if memory allocation is successful by checking if the pointer is NULL.
After using malloc/calloc, free the memory using free() to avoid memory leaks.
malloc leaves the memory with garbage values whereas calloc initializes memory to
zero.
Small Example Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int n, i;
if (ptr == NULL) {
printf("Memory not allocated.\n");
return 1;
}
printf("Enter elements:\n");
for (i = 0; i < n; ++i) {
scanf("%d", ptr + i);
}
printf("You entered:\n");
for (i = 0; i < n; ++i) {
printf("%d ", *(ptr + i));
}