LmCast :: Stay tuned in

The Double Headed Stack Allocator

Recorded: Oct. 15, 2026, 2:09 a.m.

Original Summarized

The Double Headed Stack Allocator – The blog at the bottom of the sea

The blog at the bottom of the sea
Programming, Graphics, Gamedev, Exotic Computation, Audio Synthesis

Menu
Skip to content
Table of Contents
License
Contact

The Double Headed Stack Allocator

demofox2October 3, 20265

When programming high performance applications, such as video games, you learn neat tricks for writing fast code that makes the most of limited resources.
Memory allocation is a huge topic for performance critical code that needs a variable amount of memory.
When you hear “stack allocator” you might think of “alloca” which lets you allocate memory from the actual program stack. That is super useful in a pinch, but that is not what today’s post is about. Another name for the type of stack allocator we are talking about today is “bump allocator”.
The Stack Allocator
Around 2010 I was working at Surreal Software (Midway Seattle) on an open world game “This is Vegas” which unfortunately was cancelled when Midway went out of business.
On that project, one of my duties was animation programming. Animation worked by having a state machine for sets of bones, where each state was a tree of animation blends. When states changed, they would blend out from the old state into the new state to preserve continuity.
There was a lot of blending going on, and it used a large number of dynamic memory allocations for these animations to be evaluated and blended on the CPU. These allocations were all transient though and only needed to exist for part of the frame. Furthermore, these allocations had to happen per frame, as things could change drastically from one frame to the next, as to which characters were being animated that frame – based on the camera frustum for example. The allocator showed up as a hot spot in profiling this section of code.
To solve this problem, we implemented a “stack allocator” where allocation is just an integer add, and deallocation is even cheaper.
To do this, you allocate and keep some amount of memory that is the maximum amount you will need, like say 1MB. This is your stack. You also keep an integer “tos” variable to know where the top of the stack is.
When you want to allocate memory, your memory is the memory at the top of the stack, and you add the number of bytes you want to allocate to the tos variable so that the next allocation comes after yours:

uint8_t* StackAllocate(uint8_t* mem, size_t& tos, size_t size){ uint8_t* ret = &mem[tos]; tos += size; return ret;}

In a real implementation, you would also want to know how big the memory was, so that you could handle the tos hitting the end of the memory – by returning null, or asserting, or something else.
When you are done with the memory, you just set the tos variable to 0.

tos = 0; // deallocate all stack allocations

In our case, we set the tos to 0 after animation blending was finished and we had copied the results into the buffers that were heading to the vertex shader for skinning. If you were using a stack allocator more generally for all transient memory allocations during a game’s frame, you may set it back to 0 when the frame starts.
The result was night and day. Allocation no longer took any measurable time in the profiler, because allocation was an integer addition, and freeing all memory was a single integer assigment. It doesn’t get faster than that.
One thing to note is that as written, this allocator does not call destructors or destructors. Using placement new for constructors would be easy enough. Calling destructors would be harder, as it would have to be a manual process, which is error prone. You might be able to use some RAII pattern, but stack allocators work best for simpler types.
Another great thing about stack allocators is that they can work in multi threaded environments. If the tos variable uses atomic addition, multiple threads can allocate from the same stack allocator. This can be nice in a fork/join situation on the CPU, or for a complex algorithm running on the GPU.
You can also do “partial deallocations” with stack allocators. For instance, if you had some recursive process where each level needed dynamic allocation, you could remember where the tos was when that level started, and set it back to that value when that level of processing finished.
The Double Headed Stack Allocator
A few years later, I found myself at Blizzard on the StarCraft 2 team. My boss James Anhalt was (and still is) a really smart dude who introduced me to shader toy, and shared a bunch of really cool techniques that have been previous blog posts. He told me about double headed stack allocators as a solution to a memory fragmentation problem he had hit in the past.
Imagine that you had a streaming world game where as the player ran around the world, old level geometry would deallocate, and new level geometry would allocate and stream in from disk.
At the same time, imagine the player character could shape shift into different forms – and each time they changed forms, the old form was deallocated, and the new form was allocated and streamed in from disk.
A challenge is, when you have these two systems allocating and deallocating random amounts of memory, on their own timelines, your memory is going to get fragmented.
Lets walk through a simple example. Let’s say you have 100 MB total memory for the level (red) and the character (green). The level allocates 20MB, then the character allocates 30MB, then the level allocates 20MB and the character allocates the final 30MB.
Level data (red) allocations interleaved with character allocations (green).

Now let’s say that the player runs to a new section, so the old level data memory is freed. The new level data only needs to make a single 30MB allocation. We do have 40MB memory free, but it isn’t in one chunk! We only have two blocks of 20MB. So even though the new level data is smaller, we can’t allocate space for it. This is memory fragmentation, and it’s a big problem in memory constrained environments.
Level data freed, leaving only character allocations. No room for a 30MB (3 block) allocation for new level data, despite having 40MB free!

So, James told me what they did in this type of situation was to have a chunk of memory like a normal stack allocator, but the level data had a tos which grew upwards from 0, and the character data had a tos which grew downward from the end of the memory. You knew you were out of memory when they crossed over each other and the level tos was greater than the character tos.
Let’s see how that works:
Level data (red) allocations and character allocations (green).
Level data freed, leaving only character allocations.
Level data is able to allocate the 30MB it needs by keeping a separate stack allocator in the same memory block. No memory fragmentation.

This made it so when the level data needed to change, it could reset the level tos back to 0, and reallocate the memory it needed, without any fragmentation whatsoever. Similarly, when the character freed its memory, it would reset its tos back to the end of memory, and could then reallocate the memory it needed, also without any fragmentation.
Once again, these allocators work fine in multithreaded environments, even when each thread might allocate from either side. Atomic add to the tos indices is all you need.
You might ask “why not have two stack allocators instead of a double headed one?” The main benefit is when you are memory constrained and know that the size of one stack allocator is enough to serve two systems, but the proportion of memory that goes to one side vs the other is flexible. In a game situation like described above, that means some levels could use more memory, but in those situations, the character would need to have reduced memory usage. A bit of a contrived example but hopefully you get what I mean.
Storing Variable Sized Objects In A Finite Region
There is a variation of this when you are trying to store a number of variable sized objects in a fixed amount of memory, but you want random access by index. An example may be that you want to send network packets of a specific size for efficiency reason, and you want to that memory to encode a variable number of variable sized network commands in it. You want to be able to easily iterate through the messages, but you want to support them having variable sizes too.
What you do is have a double headed stack allocator where one stack is for the dynamic allocations, and the other stack is for an array of integers that are an offset in the memory to the dynamic allocations.
Let me show you what I mean with an example. Starting with an empty double headed stack allocator:

You want to allocate 24 bytes. Stack 0 has a tos of 0, so that is where you write your 24 byte object. You add 24 to stack 0’s tos and it is now 24, where the next free region of memory is. You also allocate an integer from stack 1 and write 0 there, as the offset for where this first item lives.
Next you want to allocate 14 bytes. Stack 0 has a tos of 24, so that is where you write your 12 byte object. You add 12 to stack 0’s tos and it is now 38. You also allocate an integer from stack 1 and write 24 there, as the offset for where this second item lives.
and so on…

you also have to somehow keep track of how many objects there are. You could have a separate integer keeping count of how many offsets there are in the offset table, or maybe you could have a sentinel value in the offset table to indicate where the end of the offsets are. Perhaps ~0 (all 1s in binary) could be the sentinel value.
Just like the other stack allocators we talked about, this one can also work in a multi threaded environment. You might be tempted to make the two updates transactional – like with a compare and swap loop – but it isn’t needed.
Lastly, this configuration allows you to remove items, or move them around in memory, which is another way of reducing fragmentation – you just need to update the offset table to match reality when you do so.
Links
Another little write up that includes this topic, from the AMD vulkan memory allocator: https://gpuopen-librariesandsdks.github.io/VulkanMemoryAllocator/html/custom_memory_pools.html#linear_algorithm

Share this:
Share on X (Opens in new window)
X

Share on Facebook (Opens in new window)
Facebook
Like this:Like Loading…

Related

This entry was posted in Uncategorized. Bookmark the permalink.

Post navigation
← What To Learn To Be A Real Time Graphics Programmer Why The AI Determinism Argument Annoys Me →

5 comments

Sergii says:|

October 3, 2026 at 10:46 am

I think there is a typo in RIAA, should it be RAII

Loading...

Reply

demofox2 says:|

October 3, 2026 at 12:41 pm

Resource initialization as acquisition? Lol ill fix thanks.

Loading...

Reply

Antoine Cohade says:|

October 3, 2026 at 11:49 am

Good to read you, as usual 🙂
We’re using very similar approaches in our engine in multiple perf. Critical code paths !
One thing we noticed, though, is that the atomic multithreading approach can be quite slow (due to cache coherency trashing on the atomic counter).
Simple way to improve this is to have one allocator per thread : this ensure that the counter is always in L0$ !
Data can either be merged afterwards(additional cost, but for small-ish data, it’s still significanly faster than a single Stack), or one can use a custom iterator that runs through every thread stack.
Ps : in last exemple, there seem to be a typo where you mix 12 and 14 bytes

Loading...

Reply

Antoine Cohade says:|

October 3, 2026 at 12:02 pm

Ps: of course it depends at which frequency, and how much data you allocate, but still thought it was worth mentioning 🙂

Loading...

Reply

demofox2 says:|

October 3, 2026 at 12:40 pm

Yeah, that’s great info. Thanks for sharing!

Loading...

Reply

Leave a Reply Cancel replyCommentNameEmailWebsite Turn on JavaScript to leave a comment.

Δ


Search

Archives

October 2026 (2)
July 2026 (1)
May 2026 (1)
October 2025 (1)
August 2025 (2)
May 2025 (1)
April 2025 (2)
January 2025 (1)
October 2024 (2)
September 2024 (1)
May 2024 (1)
March 2024 (1)
February 2024 (1)
December 2023 (2)
November 2023 (1)
October 2023 (3)
September 2023 (3)
August 2023 (2)
April 2023 (1)
March 2023 (3)
February 2023 (2)
January 2023 (1)
October 2022 (1)
August 2022 (1)
July 2022 (4)
June 2022 (2)
March 2022 (2)
February 2022 (4)
January 2022 (2)
December 2021 (2)
July 2021 (1)
June 2021 (2)
April 2021 (2)
November 2020 (2)
October 2020 (1)
July 2020 (3)
June 2020 (4)
May 2020 (4)
March 2020 (4)
February 2020 (1)
January 2020 (2)
December 2019 (2)
October 2019 (1)
August 2019 (1)
July 2019 (1)
June 2019 (2)
May 2019 (2)
March 2019 (1)
November 2018 (2)
August 2018 (2)
July 2018 (2)
June 2018 (3)
April 2018 (2)
March 2018 (4)
January 2018 (1)
December 2017 (1)
November 2017 (4)
October 2017 (4)
September 2017 (1)
August 2017 (2)
July 2017 (4)
June 2017 (1)
May 2017 (2)
April 2017 (1)
March 2017 (5)
February 2017 (2)
January 2017 (3)
December 2016 (5)
November 2016 (1)
October 2016 (3)
September 2016 (3)
August 2016 (2)
July 2016 (2)
June 2016 (2)
May 2016 (1)
April 2016 (3)
March 2016 (4)
February 2016 (6)
January 2016 (1)
December 2015 (3)
November 2015 (2)
October 2015 (3)
September 2015 (5)
August 2015 (7)
July 2015 (3)
June 2015 (3)
May 2015 (2)
April 2015 (6)
March 2015 (6)
February 2015 (6)
January 2015 (3)
December 2014 (2)
November 2014 (1)
August 2014 (5)
July 2014 (1)
June 2014 (2)
May 2014 (1)
March 2014 (3)
February 2014 (3)
January 2014 (3)
November 2013 (1)
October 2013 (1)
September 2013 (3)
July 2013 (4)
June 2013 (4)
May 2013 (5)
November 2012 (1)
October 2012 (1)
September 2012 (11)
June 2012 (1)
May 2012 (3)

Categories

assembly (1)

Audio Synthesis (19)

C++ (98)

Coding Style (2)

Computer Science (74)

Cryptography (15)

DSP (1)

Encryption + Security (9)

Fractals (2)

Game Development (97)

Gamedev Commentary (4)

Graphics (87)

Math (90)

My Old Master (2)

Network Programming (1)

Neural Networks (6)

Other (1)

Path Tracing (1)

People Skills (6)

Quantum Computing (4)

Ray Tracing (16)

Research (13)

Shadertoy (10)

Skeletal Animation (3)

Uncategorized (83)

Category Cloudassembly Audio Synthesis C++ Coding Style Computer Science Cryptography DSP Encryption + Security Fractals Gamedev Commentary Game Development Graphics Math My Old Master Network Programming Neural Networks Other Path Tracing People Skills Quantum Computing Ray Tracing Research Shadertoy Skeletal Animation Uncategorized

Recent Posts

Why The AI Determinism Argument Annoys Me
October 7, 2026

The Double Headed Stack Allocator
October 3, 2026

What To Learn To Be A Real Time Graphics Programmer
July 1, 2026

My Professional Motivations, Qualifications, and Role Preferences
May 19, 2026

Using Information Entropy To Make Choices / Choose Experiments
October 5, 2025

Create a website or blog at WordPress.com

Discover more from The blog at the bottom of the sea
Subscribe now to keep reading and get access to the full archive.

Type your email…


Subscribe

Continue reading

Loading Comments...

Write a Comment...

Email (Required)

Name (Required)

Website

%d

When programming high-performance applications, especially in fields like video games, memory allocation is a critical performance factor. The author introduces the concept of a stack allocator, initially framing it as a solution for transient memory needs that occur frequently during short operational periods, such as frame-by-frame animation blending. This approach moves beyond simple stack allocation by implementing a bump allocator, where memory allocation is achieved through a simple integer addition to a top-of-stack index variable, and deallocation is achieved by resetting this index, which is extremely fast. This method eliminates measurable time spent on allocation in profilers, as the operation reduces to simple arithmetic, allowing the entire block of transient memory associated with a frame to be reclaimed with a single assignment. Although stack allocators are highly efficient, the author notes limitations, such as the difficulty in safely handling constructors or destructors, suggesting that managing Resource Acquisition Is Initialization patterns might be complex within this scheme. Furthermore, while stack allocators can be managed in multi-threaded environments when the top-of-stack index uses atomic addition, they can also be adapted to support partial deallocations and can be further extended to manage variable-sized objects by using a second stack to store offsets, which facilitates in-place memory rearrangement to mitigate fragmentation.

A more complex solution, the double headed stack allocator, was introduced to address memory fragmentation issues in memory-constrained environments, particularly in streaming applications where dynamic allocations and deallocations happen asynchronously. The problem arises when two independent systems, such as streaming level geometry and character geometry, allocate and deallocate memory concurrently; this interleaving leads to fragmentation where free memory is scattered across non-contiguous blocks, making it impossible to satisfy large, subsequent allocation requests even when sufficient total memory is available. The author proposes managing this fragmentation by employing two interacting stacks within the same memory region. For instance, one stack might track allocations growing upward from zero, while the second stack tracks allocations growing downward from the end of the memory block. By monitoring the relationship between the top-of-stack pointers of these two stacks, the system can detect when memory corruption or fragmentation risks occur. When one system completes its operation, it can reset its corresponding stack pointer to its starting reference point, allowing it to reallocate memory in a way that avoids fragmentation by utilizing the space freed by the other system. This mechanism ensures that dynamic memory operations for different systems can occur without interference, and the approach is compatible with multi-threaded execution if the indices are managed atomically.

This double headed approach also extends to managing variable-sized objects within a finite region of memory. In this variant, one stack handles the dynamic memory allocation, while a second stack stores integer offsets that point to the locations of these dynamically allocated objects. This configuration allows for efficient storage and random access to variable-sized network packets or commands. By maintaining an offset table, operations like removing or moving objects become possible by updating this table to reflect the new memory layout, effectively reducing fragmentation by consolidating free space. This structure, leveraging the interaction between two stacks and an offset map, provides a flexible and robust framework for managing complex, dynamic memory requirements in performance-critical software.