liveBook · Manning

Malloc

As explained in Modern C

malloc is the C standard library function that allocates a specified number of bytes of storage and returns a pointer to the storage or a null pointer on failure.

malloc allocates a specified number of bytes during program execution and returns a pointer to that storage, or a null pointer on failure. It supports dynamic allocation when fixed-size objects cannot accommodate growing collections or irregular data. Include stdlib.h when using malloc and its related interfaces. section 13.1

Allocating a vector

A vector containing one double for each living person can be allocated by multiplying its length by the size of one element. Writing sizeof *largeVec expresses the element type through the pointer and keeps the allocation correct if the pointer type changes. malloc itself knows neither the eventual type nor its later use; it receives only a byte count. section 13.1

Use malloc alongside the rules governing allocated storage:

  • Pair every allocation with a corresponding free; failing to do so can create a memory leak and resource exhaustion. section 13.1.2
  • Pass free only a pointer returned by malloc, calloc, aligned_alloc, or realloc, or a null pointer—not a subobject, ordinary variable, or already-freed pointer. section 13.1.2
  • Treat calloc, realloc, and aligned_alloc as specialized allocation interfaces: they clear storage, resize storage, or ensure nondefault alignment. section 13.1

How Modern C covers it

How deep it goes
Explains byte sizing, void pointers, allocation pairing, and valid free arguments, but defers implementation internals.
Examples
Uses a vector of doubles sized for one element per living person and examines platform feasibility.
What it assumes
Assumes pointers and sizeof sufficiently to express an allocation, while introducing void pointers through the allocation interface.
What you can do after
Apply malloc to allocate byte-sized storage and maintain its lifetime with a valid matching free.
How it connects
Connects malloc with dynamic allocation, void pointers, sizeof, free, calloc, realloc, aligned_alloc, and memory leaks.

Also explained in

Compare how 2 books explain malloc →

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.