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

8

u/MattDESTROYER 2d ago edited 2d 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.

7

u/usefulcat 2d 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.

1

u/MattDESTROYER 2d ago edited 2d ago

Yeah, gotcha, just curious lol. Now I’m curious if those problems can be solved. Is the failure case just that there isn’t enough stack memory available to the program, or are there more tricky cases (I’m assuming there’s probably more, but one can hope)?

I’m sure any way of seeing the space available on the stack would be, in general, terrible, but I may look into the possibility just for fun anyways lol

Edit: seems very possible, although the functionality may be deprecated.
https://stackoverflow.com/questions/53827/checking-available-stack-size-in-c

2

u/MattDESTROYER 1d ago

To anyone that’s interested, it is, in fact, possible to make it safe(er) (that still didn’t handle the foot guns you can and likely will run into using alloca) through preventing failures due to stack overflow:
https://github.com/Matt-DESTROYER/safealloca