liveBook · Manning

Resource cleanup

As explained in Modern C

Cleanup code is code that releases resources and restores required state when an operation completes or fails.

Cleanup code releases resources and restores required state when an operation completes or fails. In C, error paths must still free allocated memory and preserve required state such as errno. section 14.5

One cleanup path for exceptional exits

An optimized number-printing function allocates a buffer, enlarges it with realloc when necessary, and may encounter allocation failure or a result exceeding INT_MAX. Rather than duplicate free calls across nested conditions, it uses goto to jump to shared cleanup code. The normal path remains readable while exceptional exits converge on resource release. section 14.5

Keep the control-flow rules explicit:

  • Place cleanup at a clearly marked label within the same function. section 14.5
  • Do not jump over variable initializations. section 14.5
  • Use the technique pragmatically: duplicated or deeply nested error handling can be harder to follow. section 14.5

How Modern C covers it

How deep it goes
Explains shared cleanup control flow and three goto rules, but stops short of broader nonlocal-jump mechanisms.
Examples
Uses an optimized number-printing function handling buffer growth, allocation failure, and INT_MAX overflow.
What it assumes
Assumes C functions and dynamic allocation, while defining function-local goto labels and initialization constraints.
What you can do after
Apply it via C's goto to centralize cleanup while keeping ordinary control flow readable.
How it connects
Connects error handling with dynamic memory allocation, realloc, free, errno, and goto.

Also explained in

Compare how 6 books explain resource cleanup →

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.