Chapter 5. Memory Management

All nontrivial C programs allocate memory at runtime. The standard C library provides four memory-management routines: malloc, calloc, realloc, and free. The Mem interface repackages these routines as a set of macros and routines that are less prone to error and that provide a few additional capabilities.

Unfortunately, memory-management bugs are common in C programs, and they are often difficult to diagnose and fix. For example, the fragment

   p = malloc(nbytes);
   ...
   free(p);

calls malloc to allocate a block of nbytes of memory, assigns the address of the first byte of that block to p, uses p and the block it points to, and frees the block. After the call to free, p holds a dangling pointer — a pointer that refers to ...

Get C Interfaces and Implementations: Techniques for Creating Reusable Software 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.