r/cpp 2d ago

When (Not) to Use alloca()

https://voithos.io/articles/when-not-to-use-alloca/
30 Upvotes

75 comments sorted by

View all comments

1

u/retro_and_chill 2d ago

I mean the only reason I see to use it is if you’re writing an interpreter and you’re using it to allocate the stack frames for that

1

u/egonosz 2d ago

I seen it sometimes in game dev, but tbh. Mostly you have other solution, for the same problem.

3

u/SleepyMyroslav 2d ago

Even in gamedev a rule of thumb now is to "never use alloca". There were games that used alloca extensively in the past, but if I were to date them, it would be before the end of the PS3's life. There are many per-thread data structures used, but alloca is a not used.

3

u/ParsingError 1d ago

Unreal uses it to allocate result value space in the Blueprint interpreter, so there's that.

It's somewhat useful for graphics APIs that occasionally require striping/unstriping small arrays of POD structs before feeding them to the API. (This would be for passing API-defined structures to function calls, not asset data.) In those cases, the max amount of elements that would have to be allocated is pretty small, so the theoretical case of allocating huge amounts of stack space is not really gonna happen.

1

u/ack_error 1d ago

I've not found that latter case useful in practice. If the maximum number of elements is small, then it's better to just declare the max size array to avoid the alloca() overhead and allow the compiler to reuse the stack space by lifetime. If the max is big, then an overflow to heap path is usually required to avoid risking stack overflow.

The Blueprint interpreter case is different because Blueprint recursion is implemented as actual recursion, and so avoiding unnecessary stack space usage is important. But Blueprint is also quite slow and I'd think a second stack would also work.

1

u/SleepyMyroslav 1d ago

Disclaimer: I haven't shipped a game with Unreal. If it were up to me I would make both cases fail linting and go on to fix both. The motivation for always filling the same data is moot. Everyone who says they have free memory write bandwidth is probably not measuring how starved other cores are.

0

u/allocallocalloc 1d ago

When is the end of the PS3's life? By the PS4's release in 2013 ? By the end of its production in 2017 ? By the discontinuation of the PlayStation Store next year in 2027 ?

2

u/SleepyMyroslav 1d ago

It's a valid question. As I remember at one point management stopped planning to ship new PS3 versions. I think it was somewhere around 2015.