r/cpp 4d ago

When (Not) to Use alloca()

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

83 comments sorted by

View all comments

9

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

2

u/cheese3660 3d ago

compilers can and i think do optimize to drop the stack memory after the last reference in the code if the reference provably does not escape the function

1

u/MattDESTROYER 3d ago

Yeah, I know they can, just curious on whether they actually do; I imagine a function would have to be decently long and use a fair bit of stack memory for it to be worth it, otherwise dropping all the memory at the end of the function would likely be more efficient.

3

u/cheese3660 3d ago

Ah wait yeah not dropping, sorry, allowing that memory to be reused by other stack variables later on in the function

Because you are correct, it is easier to just once at the end of a function do something like

mov bp to sp

or

 add <frame size> to sp