Dynamic Memory Allocation in C (malloc, calloc, realloc, free with Examples)
This tutorial explains dynamic memory allocation in C, which allows programmers to allocate memory at runtime. It covers malloc, calloc, realloc, and free with syntax and practical examples for efficient memory management.
1. What is Dynamic Memory Allocation
- Dynamic memory allocation allows memory to be allocated during runtime.
- Useful when the size of data is unknown at compile time.
- Functions used:
malloc(),calloc(),realloc(),free(). - Requires
#include <stdlib.h>.
2. malloc() – Memory Allocation
- Allocates memory of given size and returns a void pointer.
- Syntax:
Example
Output:
3. calloc() – Contiguous Allocation
- Allocates memory for array of elements and initializes all to 0.
- Syntax:
Example
Output:
4. realloc() – Reallocate Memory
- Changes the size of previously allocated memory.
- Syntax:
Example
Output:
5. free() – Free Allocated Memory
- Frees memory allocated by
malloc,calloc, orreallocto avoid memory leaks. - Syntax:
Key Notes
- Always check if pointer is NULL before accessing memory.
- After
free(), set pointer to NULL to avoid dangling pointer.
6. Key Points to Remember
- Use
malloc()for single allocation,calloc()for array with zero initialization - Use
realloc()to resize memory dynamically - Always free memory after use
- Dynamic memory is essential for efficient memory management in large or variable-size programs