liveBook · Manning

Malloc

As explained in Modern C, Third Edition

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

A variable-sized array

If length is greater than zero, `double *values = malloc(length * sizeof *values);` requests space for length doubles. Check `values` before using it: a failed allocation returns a null pointer. Initialize the elements you need, then call `free(values)` when the array is no longer needed. section 13.1

`malloc`, declared in `<stdlib.h>`, allocates storage on demand and returns a pointer to it. Unlike `calloc`, it does not clear the new storage. Request a size strictly greater than zero. This makes `malloc` useful when an array’s size depends on data known only while the program runs. section 13.1

TAKEAWAY: Treat allocation and release as one lifecycle.

  • Check for a null pointer before copying into or otherwise using newly allocated storage. section 13.1
  • Match every successful allocation with a `free`. Missing releases can leak memory and exhaust resources. section 13.1.2
  • Pass `free` an allocated pointer as returned, not a pointer into its storage, an ordinary variable’s address, or a pointer already freed. section 13.1.2

A resizable circular buffer shows why this lifecycle matters: initialization allocates its data array, destruction releases it, and resizing may replace the array through `realloc`. A returned replacement pointer must not be ignored. section 13.1.1

How Modern C, Third Edition covers it

How deep it goes
Works through sizing, failure checks, and release constraints without describing allocator internals.
Examples
Uses a variable-sized double array, a string-copying strdup sketch, and a resizable circular buffer.
What it assumes
Assumes familiarity with pointers, arrays, and sizeof while introducing dynamic allocation and failure checks.
What you can do after
Practice/perform variable-sized allocation with null checks, initialization, and matching deallocation.
How it connects
Connects malloc to free, calloc, realloc, dynamic arrays, 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, Third Edition. The section links point to the parts of the book it draws on.