liveBook · Manning

Memory allocation

As explained in Modern C

Dynamic allocation is obtaining and releasing object storage during program execution rather than solely at translation or function-entry time.

Dynamic allocation obtains and releases storage during program execution, allowing programs to handle growing collections, irregular data, large matrices, and streams. Unlike declared variables or compound literals, allocated storage begins as a byte array without object type; it acquires interpretation when a value is stored. section 13.0 section 13.1

Allocating a vector

A vector of doubles can be allocated with malloc using a byte count based on the pointed-to type: `malloc(length * sizeof *largeVec)`. Writing the pointed-to type only once lets the allocation adapt if the pointer type changes. Release the storage with free when it is no longer needed. calloc provides zeroed bits, realloc grows or shrinks an allocation, and aligned_alloc requests nondefault alignment. section 13.1

Manage allocated storage with explicit ownership and matching operations:

  • Pair every allocation with a free; missing releases can create memory leaks and resource exhaustion. section 13.1.2
  • Use free only with pointers returned by malloc, calloc, aligned_alloc, or realloc, or with null pointers. section 13.1.2
  • Remember that realloc may both release the old allocation and create a new one, complicating simple allocation counts. section 13.1.2

The allocation functions operate through void pointers, so the interface carries no type information and can serve different object types. Allocation therefore requires deliberate size calculation, initialization, lifetime tracking, and eventual release. section 13.1 section 13.6

How Modern C covers it

How deep it goes
Explains allocation functions, sizing, void pointers, lifetime tracking, and invalid release cases, but defers complete initialization rules.
Examples
Uses a large vector of doubles, sizeof-based sizing, allocation-release pairs, and realloc as concrete illustrations.
What it assumes
Assumes familiarity with variables, compound literals, pointers, object lifetime, and storage duration while reinforcing initialization discipline.
What you can do after
Operate/configure storage with malloc, calloc, realloc, aligned_alloc, and free while avoiding leaks and invalid releases.
How it connects
Connects storage instances with object lifetime, storage duration, initialization, void pointers, memory leaks, and realloc.

Also explained in

Compare how 11 books explain memory allocation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.