Dynamic Memory Allocation in C
1. Definition
Dynamic Memory Allocation refers to the process of allocating memory during runtime using pointers. Unlike
static memory allocation, memory is allocated from the heap and can be resized or freed during the
program's execution.
It allows efficient memory usage when the size of data structures (like arrays) is not known at compile time.
2. Syntax
pointer = (castType *) malloc(size);
pointer = (castType *) calloc(n, size);
pointer = (castType *) realloc(pointer, newSize);
free(pointer);
- pointer: Variable that stores the address of the allocated memory.
- castType: Type of data (e.g., int, float).
- size: Memory size in bytes.
- n: Number of elements.
- newSize: New size of memory block.
3. Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
Dynamic Memory Allocation in C
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
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));
free(ptr);
return 0;
}
Dynamic Memory Allocation in C
4. Functions in Dynamic Memory Allocation
1. malloc()
2. calloc()
3. realloc()
4. free()
5. Detailed Functions
i. malloc() - Memory Allocation
- Definition: Allocates a single block of memory of specified size.
- Syntax:
ptr = (castType *) malloc(size);
- Example:
int *ptr = (int *) malloc(5 * sizeof(int));
ii. calloc() - Contiguous Allocation
- Definition: Allocates multiple blocks of memory and initializes them to zero.
- Syntax:
ptr = (castType *) calloc(n, size);
- Example:
float *arr = (float *) calloc(10, sizeof(float));
iii. realloc() - Reallocation
Dynamic Memory Allocation in C
- Definition: Resizes previously allocated memory block.
- Syntax:
ptr = realloc(ptr, newSize);
- Example:
ptr = realloc(ptr, 20 * sizeof(int));
iv. free() - Free Memory
- Definition: Deallocates memory previously allocated using malloc, calloc, or realloc.
- Syntax:
free(ptr);
- Example:
free(ptr);