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:

malloc(), calloc()

Allocate a new block of memory.

realloc()

Resize an allocated memory block.

free()

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 size_t.

Allocating Memory Dynamically

The two functions for allocating memory, malloc() and calloc(), have slightly different parameters:

void *malloc( size_t size );

The malloc() function reserves a contiguous memory ...

Get C in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.