Explain Dynamic Memory Allocation in C with Examples

«
»
This C Tutorial explains Dynamic Memory Allocation in C with examples.

In simple means, when you required 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.

advertisement

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.

advertisement

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn