liveBook · Manning

Memory allocation

As explained in Modern C, Third Edition

Dynamic allocation is a runtime mechanism that obtains storage for objects independently of ordinary declarations and releases it according to allocation operations.

Memory allocation creates storage at runtime rather than through ordinary declarations. The allocated region initially appears as a byte array; it acquires an object type when a value is stored in it. Its lifetime and visibility therefore differ from those of declared variables. section 13.0

#include <stdlib.h>
void* malloc(size_t size);
void free(void* ptr);
void* calloc(size_t nmemb, size_t size);
void* realloc(void* ptr, size_t size);
void* aligned_alloc(size_t alignment, size_t size);

The standard allocation interface includes malloc and free, plus specialized operations for zeroed storage, resizing, and alignment. section 13.1

Use allocation functions with these constraints:

  • Call malloc to obtain storage and free to release it; use calloc for zeroed bits, realloc to grow or shrink storage, and aligned_alloc for nondefault alignment. section 13.1
  • Pass a size strictly greater than zero to allocation functions. section 13.1
  • Check the returned pointer before using the storage: a failed allocation produces a null pointer. section 13.1
  • Include <stdlib.h> so the compiler sees the correct allocation interfaces; omitting it can produce an invalid assumed declaration. section 13.1

Allocate and release a vector

size_t length = livingPeople(); double *largeVec = malloc(length * sizeof *largeVec); if (largeVec) { for (size_t i = 0; i < length; ++i) largeVec[i] = 0.0; /* use largeVec */ free(largeVec); } The program computes the required runtime size, initializes each element explicitly, and releases the storage when it is no longer needed. section 13.1

How Modern C, Third Edition covers it

How deep it goes
Explains storage creation, failure handling, specialized allocation functions, initialization, and release, while deferring fuller lifetime rules.
Examples
Uses a runtime-sized double vector, explicit element initialization, malloc failure checks, and eventual free.
What it assumes
Assumes familiarity with declared variables, types, identifiers, compound literals, and recursive storage instances.
What you can do after
Operate malloc-family functions to obtain, initialize, resize, and release runtime-sized storage while checking failure.
How it connects
Connects dynamic allocation with object lifetime, storage duration, identifier visibility, initialization, and automatic storage.

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, Third Edition. The section links point to the parts of the book it draws on.