Chapter 12. Dynamic Memory Management
When you’re writing a program, you often don’t know how much data it will have to process, or you can anticipate that the amount of data to process will vary widely. In these cases, efficient resource use demands that you allocate memory only as you actually need it at runtime, and release it again as soon as possible. This is the principle of dynamic memory management, which also has the advantage that a program doesn’t need to be rewritten in order to process larger amounts of data on a system with more available memory.
This chapter describes dynamic memory management in C, and demonstrates the most important functions involved using a general-purpose binary tree implementation as an example.
The standard library provides the following four functions for dynamic memory management:
Allocate a new block of memory.
Resize an allocated memory block.
Release allocated memory.
All of these functions are declared in the header file stdlib.h. The size of an object in memory is specified as a number of bytes. Various header files, including stdlib.h, define the type
size_t specifically to hold information of this kind. The
sizeof operator, for example, yields a number of bytes with the type
Allocating Memory Dynamically
The two functions for allocating memory,
calloc(), have slightly different parameters:
void *malloc( size_t
malloc()function reserves a contiguous memory ...