Dynamic Memory Allocation in C
Dynamic Memory Allocation in C
As you know, you have to declare the size of an array before you use it. Hence, the array you declared may be insufficient or more than required to hold data. To solve this issue, you can allocate memory dynamically.
Dynamic memory management refers to manual memory management. This allows you to obtain more memory when required and release it when not necessary.
There are four library functions defined under <stdlib.h> for dynamic memory allocation.
Dynamic Memory Allocation Functions
| Function | Purpose |
|---|---|
malloc() | Allocates the requested number of bytes and returns a pointer to the first byte of allocated space |
calloc() | Allocates space for an array of elements, initializes all bytes to zero, and returns a pointer to the memory |
free() | Deallocates the previously allocated memory |
realloc() | Changes the size of previously allocated memory |
malloc()
The name malloc stands for memory allocation.
Allocates a single block of memory of the specified size
Returns a pointer of type
void*(can be typecast to any pointer type)Returns
NULLif memory allocation fails
Syntax
Example
This statement allocates memory for 100 integers. Depending on the system, it allocates 200 bytes (2-byte int) or 400 bytes (4-byte int).
calloc()
The name calloc stands for contiguous allocation.
Difference between malloc() and calloc()
malloc()allocates a single block of memorycalloc()allocates multiple contiguous blocks and initializes all bytes to zero
Syntax
Example
This allocates contiguous memory for 25 float elements, each of size 4 bytes.
free()
Memory allocated using malloc() or calloc() does not get released automatically. You must explicitly free it.
Syntax
This statement releases the memory pointed to by ptr.
realloc()
The realloc() function is used when the previously allocated memory is either insufficient or more than required.
Syntax
This resizes the memory block pointed to by ptr to new_size.
Example 1: Using malloc() and free()
Program: Find the sum of n elements entered by the user using malloc().
Example 2: Using calloc() and free()
Program: Find the sum of n elements entered by the user using calloc().
Find Largest Element Using calloc()
Example 3: Using realloc()
Programs to Try
Compile and run all example programs
Modify them to handle edge cases
Practice converting static arrays to dynamic arrays
Comments
Post a Comment