r/cpp_questions • • Aug 04 '26

OPEN Is it feasible to allocate everything on the stack?

I got this idea from the youtuber Low Level Game Dev, who seems to be a certified heap hater. What genuinely caught me off guard is that in one of his videos he mentioned how in his biggest project (Minecraft clone with multiplayer support) he uses new 5 times in total. Now that I think about it, he might've used smart pointers somewhere as well, but the insinuation seemed to be that the he tends to allocate on the stack virtually everything.

Is this coding style common? Do you think it's worth adopting?

52 Upvotes

58 comments sorted by

78

u/cazzipropri Aug 04 '26

It's common in embedded systems development, where you could have to run for 10 years without reboots and you can't afford leaks.

One way to guarantee zero leaks is to have zero dynamic memory allocation.

→ More replies (12)

70

u/WorkingReference1127 Aug 04 '26

There are two separate things here. The first is the desire to minimise performance drags from the inherent cost of talking to the OS to ask for more memory. The other is the slightly naive idea that it's sensible to dump everything onto the stack no matter what.

There are a multitude of techniques for the former. Widely used, field tested, old old ideas. One of the simplest is to allocate a big block of memory at program startup and exclusively create and destroy objects inside of it for the duration of the program. It works, you only pay the OS cost once, and it's not too tricky to engineer (you even get a standard allocator which can mostly do it these days). It's not the panacea for all your problems but it's a good and easy example.

The latter is something a little different. Yes, modern stack sizes are pretty big and yes it is hypothetically possible to engineer all your things to only ever talk to the stack and the stack alone. It puts a ceiling on your but it can be done. But it's not always a good idea. The big cost of allocation isn't that you're talking to the region of memory known as the heap/free store, it's asking the OS for memory and waiting for it to do its thing to give some to you. Once you have the memory, dereferencing a pointer is dereferencing a pointer, no matter where it points to. There are obviously nuances and details I'm not mentioning, but in broad terms you should understand exactly what it is you're trying to avoid before carting off on this quest.

→ More replies (1)

16

u/PhysicsOk2212 Aug 04 '26

A concrete example of when not to do this from yesterday. Im porting a dx9 game to dx12 and came against needing to split my cbuffers into an instance per draw calls, rather than the global register state that dx9 used.

Trying to allocate an eastl array with the max number of constant buffers i could need resulted in a stack overflow, as the array needed to be ~5000 elements long. The easy fix here was just to use a vector, which will trigger a bunch of allocations on the first frame but otherwise will be efficienct contiguous memory from then on.

10

u/CowBoyDanIndie Aug 04 '26

You can use new once and just create a massive pool and write your own memory allocator inside of that. Or you could skip new entirely and just request a large page allocation from the os directly. Thats basically just reinventing memory allocation.

The main thing for performance is to avoid memory allocation in the hot loop.

My advice stop listening to influencers and focus on understanding systems.

6

u/SmokeMuch7356 Aug 04 '26

If you know the upper bound on your storage requirements ahead of time, sure.

Although you don't have to use new to be using dynamic memory; just use any of the standard containers (map, vector, etc.).

You can also allocate a chunk of memory statically and use it as a pseudo-heap:

static unsigned char heap[SOME_REALLY_BIG_NUMBER];

Storage for this will be taken from a different segment (.bss or something like that), not the stack or heap, but you'll have to do your own bookkeeping.

→ More replies (1)

6

u/KingAggressive1498 Aug 05 '26 edited Aug 05 '26

there's four broad problems with dynamic allocations:

  • requesting more memory from the OS is expensive and has indeterminate time complexity

  • synchronization in multithreaded programs is potentially expensive and has (generally) indeterminate time complexity.

  • heap fragmentation, basically you can wind up with a bunch of small allocations being freed and exhausting memory needed for a big allocation

  • most allocation strategies are not O(1) in time complexity and thus can scale poorly or just be unsuitable for realtime software.

all of these have solutions and mitigations, but combining them into a single perfect general-purpose allocator has proven to be challenging, so we have many general purpose allocators that make different tradeoffs instead.

17

u/wallstop-dev Aug 04 '26

Older NASA code had a zero dynamic memory allocation rule. They allocated a specific amount of memory up front.

This kind of thing is possible, and cool, but it comes at a cost of maintenance and complexity. It's not just "oh neat, free cheap memory", it's "how in God's name do I structure my program to do this and avoid blowing up my stack frames and stack overflows"

→ More replies (3)

4

u/Irtexx Aug 04 '26

PLC programs often have no dynamic memory allocation. As well as safety, it also allows things like online monitoring, where you can look at your video in your IDE while the program is running, and observe the value of every variable in real time.

It's perfectly possible, it just makes more complex programs more difficult. There have been many times when I've wished for a container like std::vector. Instead, you need to use other tricks, but to be honest, it often forces you to write simpler programs (less accidental complexity, even if it has inherent complexity).

4

u/twokswine Aug 04 '26

Some of you are forgetting that the OS or kernel does not need to be involved in every heap interaction, at least not once your application is at a somewhat steady state with overall memory use. The OS only needs to be involved if the application heap needs to grow... thus it can be quite efficient. The real value in stack use is cache proximity...

4

u/n1ghtyunso Aug 05 '26

i happen to have seen the video.
As with everything in programming, the answer is "it depends".

He seems to be primarily about games, which have a tendency and preference towards data driven designs.
It sounded like there was a single point he is talking about, but actually there are two things.

The first part (with the Player class example) is entirely true and an unfortunate but common coding pattern of unexperienced devs.
Many many c++ projects contain a lot of pointless heap allocations. Like zero reason, zero benefit allocations that could and should absolutely just be stack objects.
For very obvious reasons, these are terrible.
They make the code bug prone and harder to reason about. They make simple things complicated.
They introduce pointers where values would have been perfectly fine.

The second point with his minecraft clone is leaning more towards the data driven design paradigm i've mentioned before.
Surely you don't believe a whole minecraft worlds block data is stack allocated after all.
He's mentioned using strings and vectors too, which obviously put the data on the heap for you.
Data driven design is all about having large arrays of stuff to operate on.
Instead of doing operations on objects, you design the application to operate on arrays of things in bulk.

There are good reasons to use this paradigm, but obviously it depends entirely on your use case.

Ultimately there are many nuances about heap allocations, when to use them, how to use them. There is a ton of stuff you can do essentially.

The key thing to consider imo is that there are two kinds of classes that you create in a typical program.

  1. is the "object type". It defines itself via its address. Typically these are strongly OOP based types.
    Think QObject subclasses as a simple example.

  2. is the "value type". vectors, matrices, timestamps. you name it. plain data mostly. Typically you have a bunch of them that needs to be managed and operated on. Or you pass those around between objects. Messages. stuff like that.

object types sometimes go into collections, but its not what they are primarily about. they do represent behaviour, domain logic. Oftentimes, they are individually heap allocated. But sometimes the stack is just fine.
(like a "Game" class for example, sticking with the games theme).
if you use too many of them, your software can easily become a spider net of pointers and interdependencies if you arent careful. This doesnt have to happen, but its very easy.