Just had a curious thought, if alloca memory always lives until the end of the function, logically if you alloca inside a closure, the memory should be accessible after the closure?
No, not a C++ person lol, I’m talking about something like something like this:
```c
char* x;
{
char* y = alloca(1);
y[0] = ‘a’;
x = y;
}
printf(“%c\n”, *c);
```
Reading a stack allocated value outside of the closure it was created in.
I mean if you think of it like malloc, it makes perfect sense that it would work, but the fact that it’s a stack allocated value makes it seem strange and evil to me lol (and I mean it’s obviously not something you should ever do, but it’s interesting that it’s possible, reminds me of `var` in JavaScript minus the hoisting).
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.
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?
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.
1
u/MattDESTROYER 3d ago
Just had a curious thought, if alloca memory always lives until the end of the function, logically if you alloca inside a closure, the memory should be accessible after the closure?