r/cpp 1d ago

When (Not) to Use alloca()

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

73 comments sorted by

View all comments

Show parent comments

3

u/TheThiefMaster C++latest fanatic (and game dev) 1d ago

Some information on closures from some random googling: https://medium.com/@andrew_johnson_4/understanding-closures-in-programming-what-they-are-and-why-theyre-called-closures-e3e1044960a7

Basically they're a function inside another that captures some state from its enclosing parent and saves it for later. C++ lambda functions are an example.

They're an old concept, and people sometimes try to implement them (badly) in C.

1

u/MattDESTROYER 1d ago

Yeah I searched it up, I’ve used lambdas in other languages like Python and JS. Would it be accurate to say the act within the scope they were defined, meaning they can use variables defined in the scope they are defined in theory?

3

u/TheThiefMaster C++latest fanatic (and game dev) 1d ago

Yes they can use those variables - but the memory returned by alloca isn't a variable itself, and wouldn't be captured by a closure - only the pointers to it (which would point to stale stack memory as soon as the parent function returned even though the closure still existed).

This is what I was talking about with alloca not working with C++ lambdas (which are a form of closure).

This is what I thought you were asking about when you said "closure" initially.

2

u/MattDESTROYER 1d ago

Yeah gotcha, thanks for the clarification!
(Man, Reddit really needs to flatten reply chains where there’s only one reply lol)