main()callscreatePdf()createPdf()callsdrawPage()drawPage()callsfetchText()

- Return address (where to continue after return)
- Function arguments
- Local variables
- Saved registers required by the calling convention
fetchText() returns, its frame is popped and control goes back to drawPage(); memory is reclaimed by adjusting the stack pointer. This LIFO discipline keeps stack memory contiguous and cache-friendly.
Heap: flexible storage for variable-sized and long-lived objects
In contrast, objects that must outlive the creating function or whose size is only known at runtime belong on the heap. For our PDF example, page buffers, images, and document content often must remain after drawPage() returns, so they are allocated on the heap.
Heap allocation requires an allocator (e.g., malloc/free) to find a free region large enough, update metadata, and possibly split/coalesce blocks. Since allocations vary in size and lifetime, bookkeeping and searching introduce overhead and can cause fragmentation over time — which makes heap allocation generally slower than stack allocation.

Stack overflow from deep recursion or very large stack-allocated objects will crash the program. In native languages, failing to
free heap allocations leads to memory leaks and potential out-of-memory conditions. Use safe limits and profiling tools.- Prefer stack allocation for small, fixed-size local variables whose lifetime is bounded by the function.
- Use heap allocation when you need dynamic-sized buffers or objects that outlive their creating function.
- Avoid very large automatic (stack) arrays; use heap allocation if the size can be large or unbounded.
- In manual-memory languages (C/C++), always pair allocation and deallocation (
malloc↔free,new↔delete) and prefer RAII or smart pointers to avoid leaks. - Watch recursion depth and set appropriate stack limits when necessary.
- Profile heap usage and fragmentation with allocator-specific tools (e.g., malloc profiling, valgrind, sanitizers).
- Choose modern, hardened allocators (tcmalloc, jemalloc, hardened glibc allocators) when performance or security is a concern.
Stack frames are ideal for fixed-lifetime, small, short-lived data (local variables and return context). Heap storage is used for variable-sized or longer-lived data that must outlive the creating function.