liveBook · Manning

Realloc

As explained in Modern C

realloc is a C standard library function that changes the size of a previously allocated memory block while preserving its existing contents up to the applicable size.

realloc changes the size of an existing dynamically allocated storage instance. It receives the existing pointer and a requested byte size, then returns either a pointer to storage of the new size or null. section 13.1.1 section 13.1

TAKEAWAY: resizing changes pointer validity and preserves only the applicable prefix.

  • The returned pointer may equal the argument or identify a relocated object; do not continue using pointers derived from the original object. section 13.1.1
  • Enlarging preserves the original-sized prefix, while shrinking preserves the prefix that fits the new size. section 13.1.1
  • Check the return value before replacing the stored pointer; the circular-buffer implementation returns failure when resizing cannot be fulfilled. section 13.1.1
  • Treat realloc as both deallocation of the old object and allocation of the new one when tracking allocation and free pairs. section 13.1.2

Growing a circular buffer

A circular buffer can resize its backing array with `ntab = realloc(c->tab, sizeof(double[nlen]));`. After checking `ntab`, the implementation handles data that wraps across the old array boundary: it copies one chunk upward with `memcpy` or moves the other chunk with `memmove`, then stores the new capacity, start position, length, and table pointer in the structure. section 13.1.1

Only pass allocation pointers, including a pointer returned by realloc, to free; never free a pointer into the middle or a smaller part of an allocated object, or reuse a pointer after it has been freed. section 13.1.2

How Modern C covers it

How deep it goes
Explains return-pointer relocation, prefix preservation, failure checks, and allocation accounting, while deferring broader implementation details.
Examples
Demonstrates realloc on a double array backing a circular buffer whose live data may occupy two wrapped chunks.
What it assumes
Assumes dynamic allocation, malloc, free, pointers, and byte-sized storage, while relating realloc to the void-pointer allocation interface.
What you can do after
Apply it via stdlib.h to resize allocated arrays, check failure, update the owning pointer, and preserve or relocate live data safely.
How it connects
Connects realloc with malloc, calloc, aligned_alloc, free, void pointers, dynamic allocation, memcpy, and memmove.

Also explained in

Compare how 2 books explain realloc →

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.