Alloca for temporary float buffers

More of a general programming question than JUCE specific I guess, but was hoping someone here could shed some light on this one:

I’ve been using alloca to make intermediate float buffers for audio processing.

like this:

float* tempBuffer = (float*) alloca (length * sizeof (float));

In practice I have never had a problem with that and it seems to work well. And I have read that alloca just points to memory on the stack, so it should be as safe as making a new variable. But just wanted to check here if that looks ok?

If not, is there a better practice?

If you grep the JUCE modules you can find few alloca.

nicolasdanet@MacBook-Air-de-Nicolas modules % grep -r "alloca (" ./
.//juce_graphics/native/juce_mac_CoreGraphicsContext.mm:    auto data = (CGFloat*) alloca ((size_t) numColours * 5 * sizeof (CGFloat));
.//juce_graphics/geometry/juce_EdgeTable.cpp:                        auto oldTemp = static_cast<int*> (alloca (tempSize));
.//juce_graphics/geometry/juce_EdgeTable.cpp:    auto* tempLine = static_cast<int*> (alloca ((size_t) (numPixels * 2 + 4) * sizeof (int)));
.//juce_core/text/juce_TextDiff.cpp:            auto* scratch = (int*) alloca (scratchSpace);
.//juce_dsp/frequency/juce_FFT.cpp:            performRealOnlyForwardTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
.//juce_dsp/frequency/juce_FFT.cpp:            performRealOnlyInverseTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
.//juce_dsp/frequency/juce_FFT.cpp:            auto* scratch = static_cast<Complex<float>*> (alloca ((size_t) factor.radix * sizeof (Complex<float>)));
.//juce_dsp/widgets/juce_Bias.h:            auto* biases = static_cast<FloatType*> (alloca (sizeof (FloatType) * len));
.//juce_dsp/widgets/juce_Gain.h:            auto* gains = static_cast<FloatType*> (alloca (sizeof (FloatType) * len));

I guess that it means that it is not 100% evil! :wink:

I use alloca only in very specific cases (mostly in C codes) when i know that the length is small and/or the function call can NOT be recursive… and that efficiency matters (such as in DSP)! I use it only after considered preallocating cached memory on the heap first. The problem with alloca is that it could make your app crash with a stackoverflow (specially with a small stack size on some OS).

My 2 cents.

I quickly looked in my projects to find alloca examples, and it seems that i don’t use any!

I’ve been seeing crash reports from M1 macs that were near a call to alloca. I can’t confirm that is the cause yet, but I’m wondering if sandboxed plugins in Logic have a lot less call stack available to them? Anybody else seen anything like this?