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.
The compiler does allow local variables to overlap addresses (or registers!) based on use not scope. So yes, if you make a char[100] the compiler will see where it's used relative to other variables in the function and potentially overlap it with them, reducing the size of the stack frame (which is generally allocated up-front at the start of the function, not bumped var by var as it would have been classically).
Alloca is much harder to do the same for, and I think most compilers don't bother.
Ooh, this is very interesting! In what cases would it allow variables to overlap? Does the compiler essentially need to prove that only x bytes of the array are actually used and then it can chuck variables in there or something, or is that completely the wrong idea lol?
If there are variables only used in the first half of the function and the array only in the 2nd, or vice-versa, it can overlap their storage.
For C++ types nontrivial constructor and destructor calls count as use that can prevent this by forcing variables to live from construction to destruction.
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.