System Design · Concept Library · Free article
Where Your Program’s Memory Goes
Follow a familiar prefix-sum program through memory, stack frames, heap arrays and cleanup.
Memory holds the data a running program needs. The call stack tracks active function calls; heap allocations can keep arrays alive beyond the call that created them. In a prefix-sum program that preserves its input, the input and answer arrays must coexist. Peak memory depends on those overlapping lifetimes, and a valid access needs both an in-range offset and a still-live allocation.
Memory is where your running program keeps its work
When you solve an array problem, you think about values: nums[0] is 3, a running sum becomes 4, and an answer array grows. The computer also needs somewhere to keep each value while the program uses it. That working storage is memory. Creating an array is therefore more than naming a sequence. Somewhere, enough storage must be made available for its elements.
Picture memory as a long row of numbered byte-sized boxes. A byte holds eight bits. A number can occupy several boxes; an array can occupy many consecutive boxes. The number identifying a box is its address. When you write nums[i], the implementation uses the array’s representation to find the element’s storage. You do not normally write that address yourself, but the load still has to reach the right bytes.
This lesson follows one task you may already know: build a prefix-sum array. We will first name the two storage roles, stack and heap, then follow the program through them. By the end, an allocation failure should feel like a problem you can reason about from your own code.
Stack remembers the call; heap keeps the arrays
Your program needs to remember two kinds of things. First, what is this function doing right now? Which call is active, where should it return, and what are its local working values? Second, which objects must remain available? An input array might already exist before a helper starts, and an answer array might need to survive after that helper returns.
The call stack organizes active function calls. Each call gets a frame, a small record associated with that invocation. If main calls prefixSums, the helper’s frame sits above main’s. When the helper returns, its frame is removed first. This is the same last-in, first-out rule as the stack data structure you use for matching brackets. The call stack is the runtime’s use of that rule; it is not the binary heap used by a priority queue.
The heap is storage used for dynamically allocated objects whose lifetimes need not follow call nesting. In our example, the input and output arrays live there. The helper can return a reference to the output while its own stack frame disappears. The heap is not a separate stick of RAM from the stack. These are different ways of organizing a program’s memory.
This picture describes a common implementation model. A compiler can keep some locals in registers, optimize them away or place objects differently. Managed runtimes also have their own frame and object representations. The useful distinction is between the lifetime of a call and the lifetime of the data it uses, not a rule that every local variable must physically sit on a stack.
| Question | Call stack | Heap in our model |
|---|---|---|
| What belongs here? | main and prefixSums call frames | input and output array storage |
| How does it end? | A function returns; its frame is removed | The object is released or reclaimed when its lifetime ends |
| Can the answer outlive the helper? | The helper frame cannot remain a valid returned local buffer | The heap answer can remain live for the caller |
The task: keep the input and return running totals
Given [3, 1, 4, 1, 5, 9, 2, 6], return [3, 4, 8, 9, 14, 23, 25, 31]. Each answer is the sum from the start through that position. The caller still wants the original input afterward, so this version must not overwrite it.
Here is language-neutral pseudocode. new Int32Array(n) means a new, separate packed array, and function arguments are references to arrays in this example. The notation is chosen to make the memory decisions visible, not to promise a particular language’s runtime layout.
function prefixSums(input):
output = new Int32Array(length(input))
total = 0
for i from 0 to length(input) - 1:
total = total + input[i]
output[i] = total
return output
input = [3, 1, 4, 1, 5, 9, 2, 6]
answer = prefixSums(input)
use(answer)
You may have called this O(n) time and O(n) extra space. That is correct for this version. Now we will look at what that extra space actually means while the function runs. The running total and loop index are small working values. The output has n elements, so its storage grows with the input length.
A variable that finds an array is smaller than the array itself
After creating input, the program needs a way to find it again. A reference or pointer refers to an object or its storage, depending on the language. Think of input as giving the program access to the array, rather than containing all eight integers inside the variable’s name. In our call diagram, a reference belongs to the call’s working state while the array’s element storage is in the heap.
Calling prefixSums(input) gives the helper access to that same input array. It does not copy all eight elements in this reference-based example. Likewise, assigning other = input shares the array. Making an actual element copy needs new storage. The distinction matters in DSA: updating an aliased mutable array can affect what the caller sees; updating an independent array need not.
Language semantics decide which case an expression means. Python assignment binds names rather than copying objects; C++ value containers can copy their elements on assignment. Even a shallow copy of a container of references can still share the objects those references point to. Our packed integers keep the example simpler. The Python copy documentation explains the reference and shallow/deep-copy distinction for that language.
In this example, passing a reference shares the input array. Copying its elements adds a second 32-byte allocation. The helper frame ends on return, while its heap answer remains live for the caller. Use JavaScript to step through these states.
Try the two choices above. An extra reference leaves two arrays in total: input and output, 64 heap bytes. An element copy adds scratch, making three arrays and 96 bytes. The diagram shows storage reservations; it does not simulate copying individual values. This is why a line that looks harmless in a solution can change peak memory without changing the answer.
Follow the function from call to return
Start before main runs. Then advance one step at a time. First main gets a frame and input gets 32 heap bytes. Calling the helper adds a second frame. Creating output reserves another 32 heap bytes. Both arrays now exist together.
Inside the loop, the first iteration reads 3, makes total 3 and writes output[0]. The next reads 1, makes total 4 and writes output[1]. The loop reuses the same total and index storage while filling different output elements. It does not need one new running-total variable for every iteration.
The visualizer focuses on the lifetime events around that loop. Its representative reads check whether the storage is valid; the arithmetic above gives the expected values. The exact 8-byte main and 16-byte helper frames are teaching choices, not a compiler-generated layout.
In this example, passing a reference shares the input array. Copying its elements adds a second 32-byte allocation. The helper frame ends on return, while its heap answer remains live for the caller. Use JavaScript to step through these states.
Pause immediately after the helper returns. Its frame is gone, but output is still visible. That is the point of keeping a result in storage whose lifetime can outlast this call. The caller receives a reference to the answer and can use it. Returning a reference does not require making a second copy of all the output elements in this example.
Now continue through cleanup. Releasing input makes its region available for reuse. Releasing output does the same after the caller finishes with the answer. The released cards become dashed placeholders because those allocations are no longer live. The program has ended their valid use; we are not claiming that every physical bit was erased.
Why a 32-byte answer can fail in a 48-byte heap
An allocation asks for a region of storage. An allocation’s lifetime is the interval during which that region is valid for its object. Live memory counts the allocations whose lifetimes have not ended. Peak live memory is the largest amount live at one time.
Our input is 32 bytes and the output is 32 bytes. The largest single array is only 32 bytes, but allocating output while input is still live needs 64. A 48-byte budget leaves only 16 bytes after input, so the output request fails. The budget is not checked separately against each variable. It has to accommodate their overlap.
When the request is refused, peak heap use is 32 bytes, not 64: the output never acquired its storage. Increase the budget to 64 and the run can reach a 64-byte peak. At the end, both arrays can be freed, bringing live heap use back to zero. A final value of zero does not tell you how much memory the program needed along the way.
| Moment | Live arrays | Heap bytes |
|---|---|---|
| Input created | input | 32 |
| Output allocated | input + output | 64 |
| Helper returns | input + output | 64 |
| Caller releases input | output | 32 |
| Caller finishes with answer | none | 0 |
In an asymptotic analysis, this version uses O(n) additional output storage and O(1) loop bookkeeping. Some problem statements exclude the returned output when asking for auxiliary space. Always state the convention. The machine still needs bytes for that output either way. Big-O hides constants and absolute limits; the allocation ledger explains why a theoretically linear-space solution can still exceed a particular memory limit.
Can we get the peak down without changing the answer?
First look for storage the algorithm does not need. Suppose you copied input into scratch to inspect it while debugging. Debugging is over, and the prefix loop reads the original input. Keeping scratch until the end makes input, scratch and output overlap: 96 bytes. If scratch has no remaining readers, release it before allocating output. The output can reuse that region, and the peak falls to 64.
That repair removes unnecessary retention. It does not justify freeing input early: the prefix loop still reads input. A region is safe to release because all required uses are finished, not because another allocation needs room.
An in-place prefix-sum algorithm could overwrite input and avoid a separate answer array. But our caller asked to keep the original. Changing to in-place updates would change that contract. Likewise, streaming input and emitting each running sum can use bounded working storage only if the caller accepts streamed input/output rather than retaining both full arrays. The arithmetic can stay familiar while the interface changes what must remain in memory.
This is the connection to DSA optimization: before calling a solution O(1) extra space, ask what it overwrites, what it returns and who still needs the original data. A lower memory number is useful only if the required behavior survives.
An index can be in range and still be invalid
Eight four-byte elements occupy 32 bytes. If the array starts at heap+32, element i starts at 32 + 4 × i. The last element starts at heap+60 and occupies bytes 60 through 63. Element index 8 would start outside the array. That is a bounds error. The lab’s read output 28 uses a byte offset: it checks the first byte of element 7, not element 28 or an entire four-byte load.
There is a second check: does output still exist? If the helper frees output and then returns a reference to it, the caller has a reference to storage whose lifetime has ended. Even index 0 is no longer a valid access through that object. This is use-after-free. Returning a pointer into a dead local stack buffer has a similar lifetime problem: the frame has already been released.
The repair is to keep the heap result alive through the caller’s last use. Ownership means responsibility for that lifetime and cleanup. In our example, the helper creates the answer, then the caller becomes responsible for its eventual release. The lab records which frame created an allocation; it does not enforce a language-level ownership or borrowing system. We express the handoff by placing the release after the caller’s read.
Calling free twice is not extra cleanup. It is a repeated release of an allocation that is no longer live. Our model refuses dead reads, out-of-bounds reads and repeated releases with an explanation. Unsafe native code may instead have undefined behavior, corrupt data or fail much later. A neat simulator diagnostic is not a promise about the real language.
What if my language never asks me to call free?
The lifetime question still exists; the responsibility is handled differently. In manual memory management, code explicitly allocates and releases storage. In C++, an owning object can arrange cleanup through its destructor, often using RAII: resource acquisition is initialization. A smart pointer or container can tie release to its own lifetime. In a garbage-collected runtime, the runtime can reclaim objects that are no longer reachable through the references it tracks.
A Python or Java programmer should not read the lab’s free instruction as an API they need to add after every array operation. Here it makes the end of a storage lifetime explicit. Dropping one reference does not necessarily make an object unreachable, and becoming unreachable does not promise immediate reclamation in every runtime. Another object, cache or collection might still refer to the array.
A memory leak retains memory that should have been released or made reclaimable. Keeping an unnecessary array in a global list can retain it even in a garbage-collected language. By contrast, an intentionally retained answer is not a leak merely because its creator has returned. The question is whether the program still needs it and whether its eventual cleanup is accounted for.
Releasing heap storage generally makes it reusable by the allocator. It does not necessarily return physical RAM to the operating system immediately. Allocators can retain regions for later requests, and physical residency is a separate part of virtual memory management. Your task manager is not simply displaying the sum of live array element sizes. OSTEP’s Memory API chapter covers allocation, release and common errors; Cornell’s stack/heap notes explain the conventional layout.
Enough free bytes can still be the wrong shape
Imagine running prefix sums for many small inputs. Earlier calls used temporary buffers, and some obsolete buffers were not released yet. Four 16-byte reservations fill a 64-byte heap. Release the first and third. You now have 32 free bytes, but they are two separate 16-byte holes. A new packed 32-byte answer cannot fit into either hole.
This is external fragmentation. The free space exists, but not as one sufficiently large region. Our allocator uses first fit: scan from the lowest address and use the first hole large enough. It joins neighboring free regions but does not move live objects. Releasing the second obsolete buffer joins the first three regions into a 48-byte hole. The 32-byte answer then fits.
The final experiment isolates this cleanup problem. All four old buffers are explicitly obsolete, so releasing them does not discard required input. It is not permission to free arbitrary live arrays. Real allocators also have alignment, size classes and bookkeeping overhead; some managed runtimes can compact movable objects. This tiny model leaves those mechanisms out so you can see why total free bytes and the largest available hole answer different questions.
Recursion spends memory even without another array
Our iterative prefix-sum helper has one active helper frame. A recursive version that calls itself once per element can have O(n) active frames before those calls return, even if it never allocates another heap array. Each frame needs enough state to resume its own call. That is why a recursive solution can hit a stack limit while its arrays still fit in the heap.
A frame’s actual size depends on the compiler, runtime and function. Tail-call optimization is not something to assume unless your environment guarantees it. The lab uses separate stack and heap budgets so increasing one cannot silently rescue exhaustion of the other. Code, static data, runtime metadata, registers and physical pages are outside its accounting. These omissions keep the model bounded; they do not mean those parts of a real process use no memory.
Your turn: repair four versions of the memory plan
You have already seen the successful call. Now each guided experiment starts with a specific broken memory schedule. Run it once before changing anything. Name the allocation or access that failed, predict one repair and run again. The goal is to explain the evidence, not guess until the status changes.
The editor uses a small vocabulary: enter starts a call frame, leave returns from the top call, alloc reserves heap bytes, free releases an allocation and read checks a byte offset. These operations expose decisions usually hidden beneath your code. They do not execute arbitrary source code or calculate the prefix-sum values.
- Make room for the answer: fit the required input and output arrays together.
- Release an unnecessary copy: lower the peak without discarding required input.
- Keep the returned answer alive: move cleanup after the caller’s last use.
- Join the free space: release obsolete buffers so one contiguous answer region can fit.
Memory demand depends on which allocations are live at the same time. Step through calls, allocations and releases to inspect peak heap use, reusable space and allocation failures. Repair four guided schedules: budget for the answer, release an unnecessary copy, keep a returned result alive and join fragmented free space.
Open The memory lifetime workbench. Editable controls require JavaScript; the worked examples above and below remain readable.
Published by GOAT Engineer. Privacy policy · [Contact](mailto:[email protected]).
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.