O'Reilly logo

C Interfaces and Implementations: Techniques for Creating Reusable Software by David R. Hanson - Princeton University

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

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