Dynamic Memory Allocation

C 129 views Dec 22, 2025 2 min read

Dynamic Memory Allocation (DMA) allows a program to allocate and deallocate memory at runtime using functions provided in stdlib.h.


Need for Dynamic Memory Allocation

  • Memory size can be decided at runtime

  • Efficient use of memory

  • Useful when size of data is unknown in advance


Memory Allocation Functions

FunctionPurpose
malloc()Allocates single block of memory
calloc()Allocates multiple blocks and initializes to zero
realloc()Resizes previously allocated memory
free()Releases allocated memory

1. malloc() Function

Allocates memory without initialization.

Syntax

ptr = (data_type *)malloc(size_in_bytes);

Example

int *p = (int *)malloc(5 * sizeof(int));

2. calloc() Function

Allocates memory and initializes all bytes to zero.

Syntax

ptr = (data_type *)calloc(n, size);

Example

int *p = (int *)calloc(5, sizeof(int));

3. realloc() Function

Changes the size of previously allocated memory.

Syntax

ptr = (data_type *)realloc(ptr, new_size);

4. free() Function

Releases allocated memory.

Syntax

free(ptr);

Example Program

#include #include int main() { int n, i; int *p; printf("Enter number of elements: "); scanf("%d", &n); p = (int *)malloc(n * sizeof(int)); for (i = 0; i < n>scanf("%d", &p[i]); } for (i = 0; i < n>printf("%d ", p[i]); } free(p); return 0; }

Differences: malloc() vs calloc()

Featuremalloccalloc
InitializationNoYes (zero)
ArgumentsOneTwo
SpeedFasterSlower

Advantages of DMA

  • Efficient memory usage

  • Flexible memory allocation

  • Prevents memory wastage


Precautions

  • Always check for NULL pointer

  • Free memory after use

  • Avoid memory leaks


Summary

  • DMA allocates memory at runtime

  • stdlib.h provides DMA functions

  • malloc, calloc, realloc, and free are used

  • Proper memory management is essential

Some advanced sections are available for Registered Members
Share this Post
🚀 Want to Test Your Knowledge?

Take quizzes related to this topic and see where you stand!

Start Quiz Now
Back to Tutorials