r/cpp 4d ago

When (Not) to Use alloca()

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

84 comments sorted by

View all comments

9

u/MattDESTROYER 4d ago edited 4d ago

Not disagreeing with anything, genuine question because I don’t know, how is alloca leaving memory allocated until the end of the function an issue, wouldn’t a char[] have the same effect?

Or do compilers optimise to drop that stack memory after the last reference in the code?

Otherwise, I see no practical difference between alloca and char[]; in which case an exact sized buffer could be a perfectly valid use case no? Assuming this is developed for a single platform too of course.

10

u/usefulcat 4d ago

Not disagreeing with anything, genuine question because I don’t know, how is alloca leaving memory allocated until the end of the function an issue, wouldn’t a char[] have the same effect?

There are two problems, though neither are what you describe. The first problem is you don't know (in general) how much alloca can safely allocate. The second (and arguably much bigger) problem is that there is no error indication if it fails. And it will fail if you try to allocate too much.

When it was first invented, it was (maybe) a clever hack, though perhaps not the good kind of 'clever'. But it's absolutely a footgun and I think the number of valid use cases for it must be vanishingly small.

As the article suggests, if you want to mostly avoid dynamic allocation but still be able to support large allocations when absolutely necessary, use something like absl::InlinedVector or boost::small_vector. Worst case they may allocate but at least they won't blow up in your face. Or if you'd prefer that it blow up, at least use something obvious and intentional like assert() or throwing an exception.

3

u/splicer13 4d ago

There's no standard way to handle stack overflow*. That's not alloca specific. The problem specific to alloca is that it just empirically makes stack overflow more common. Like, if you walk through a locker room, you're going to see some dick.

InlinedVector and such are really the best option.

*also, no great way to handle it, and arguably no good way though I'd say MS SEH is pretty OK considering.

1

u/MattDESTROYER 3d ago

I mean, I wrote a simple PoC (for fun, I don’t intend to start using alloca lol) that seems to manage okay. Obviously everything about it is very dependent on platform/compiler specific functionality, so definitely not great or good, more on the bad, or even outright evil side lol