O'Reilly logo

C in a Nutshell by Tony Crawford, Peter Prinz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 block whose size in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required