Core · Module 4 · Lesson 4 of 9
Heap Allocation with malloc, calloc, and realloc
Master dynamic heap memory lifecycles, inspect allocator chunk metadata, and resize memory buffers safely with realloc.
Pro — members onlyAbout 17 minutes
By the end you can
- Allocate uninitialized and zeroed heap buffers using malloc and calloc
- Inspect how heap allocators store block metadata headers preceding returned pointers
- Grow and shrink memory buffers safely without memory leaks using realloc
- Prevent arithmetic integer overflow when calculating allocation byte sizes
Builds on Enumerations and Typedef Abstractions.
01 · A question first
Why does writing p = realloc(p, new_size) cause a permanent memory leak if the system runs low on RAM? And how does free(ptr) know exactly how many bytes to release when you never pass a size argument to free?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- Why it is correct
- What it costs
- Pitfalls and variations
- Where it is used
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem