This C Tutorial explains Dynamic Memory Allocation in C with examples.
Dynamic memory allocation in C is the process of manually allocating memory during runtime when the size of the array you declared is insufficient. In simple means, when you required the desired amount of memory, you are allocated, you worked up with and when you no longer needed that chunk you freed that back to the system. This way, you worked efficiently with memory usage i.e. program didn’t retain memory until it exited.
Consider an instance, suppose we need to maintain record of each employee in some organisation with new employees to join, older employees might leave, how about performing this efficiently using dynamic allocation. When new employee joins, we allocate memory and we free up when some one leaves. The memory returned to the system might be used by other parts of the same program or by other processes when they would require.
Let’s consider another example of dynamic allocation. Suppose, we read a line of input from a file, we required dynamic allocation and this grows when we read more of it from the file.
Dynamic allocation, actually, is of interest where we are not sure, in advance, until run time, how much memory would we require and this could grow if needed more of it and for how long. Further, we free up block when we are no longer required it. Remember that freeing up block at the end of program has no significant importance of dynamic allocation since all memory allocated to program returns when program exits.
Memory allocated to a program during compile time can’t be freed until program exits.
Two functions viz. malloc() and free() maintain free pool of available memory for dynamic allocation to programs.
The four functions in the <stdlib.h> header file allow for dynamic memory allocation in the C language. They are:
- malloc()
- calloc()
- realloc()
- free()
1. malloc(): It is used to dynamically allocate a single large block of memory with a specified size.
2. calloc(): It is used to allocate a certain amount of memory and then reset it to zero.
3. realloc(): It is used to resize a memory block that was previously allocated by malloc or calloc.
4. free(): It is used to de-allocate the memory.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for Computer Science Internship
- Check C Books
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for C Internship