5 ms·
So the massive stack grab isn't permanent. Conceptually, if the compiler could just inline all of the child calls, it's fine. But if this call won't return for
by jfoutz 2y ago
So the massive stack grab isn't permanent.
Conceptually, if the compiler could just inline all of the child calls, it's fine. But if this call won't return for a long time, or may be called again (even worse). You're setting aside stack that you'll never get back. Which is a memory leak, and your program will crash.
- alexchamberlain 2y agoThat reasoning leads me to conclude the function should be short lived or the memory in use by all child functions, rather than it has to be a leaf function?
- jfoutz 2y agoyeah. Leaf is a good rule of thumb, but if you need a little helper to do something it's generally fine. you really do need confidence the little helper can be fully inlined. if the helper is out of your control, and someone greatly expands its responsibility, it can suck. So, yeah, effectively a leaf.
- bombela 2y agoThe stack grab is as permanent as any other stack variable. There is nothing special about it. The only difference is that you can decide at runtime how much to add to the current stack frame.
- mypalmike 2y agoIf the memory's lifetime correctly coincides with the function (which is why you might use alloca in the first place), I don't see how this would be a memory leak nor why it would lead to a crash. Maybe on systems which limit stack size...?
- jfoutz 2y agojust don't do this. int a(){ void* mem = allocal(some_number); b(); } int b(){ a(); } if a() is a leaf (or can be trivially inlined) it's fine! on the other hand, if a() calls something else, that's complicated, it's way way harder to figure out why you're crashing. I think you'll segfault as a() eventually overwrites malloc'ed memory. but different systems are going to have different characteristics. It's not that you can't, you just have to be real damn smart and make sure no one ever messes with your code. or you can just make sure it's a leaf. much easier rule, much easier to explain.
- bombela 2y agoYour example behaves the same with or without alloca. It will run until it runs out of stack. Or it might just run forever because the compiler optimized it as an infinite loop. In any case, same behavior.
- jfoutz 2y agoTrue. How would you modify it to get the point across? Or am I crazy, and there is no point to being careful with alloca?
- bombela 2y agoMaybe if alloca is used with a runtime value uncapped, a user could then trigger a stack overflow with too big of an allocation. This is the same problem when allocating on the heap, with the difference that the heap is a few order of magnitude larger. That is really the only difference between `in foo[...N] = ...N` and alloca(n). alloca works with a value computed at runtime. And this value could be from an input.