I'm quite unconfortable with the approach however:
- Am I missing some obvious danger of alloca ?
You pointed the one real danger out: stack overflow behaviour is undefined for alloca
. In addition, alloca
isn’t actually standardised. For instance, Visual C++ has _alloca
instead, and GCC by default defines it as a macro. That problem can be circumvented fairly easily, however, by providing a thin wrapper around the few existing implementations.
- Is there a better way to avoid heap allocation here ?
Not really. C++14 will have a (potentially!) stack allocated variable-length array type. But until then, and when you consider std::array
not to be a good fit, go for alloca
in cases such as yours.
Minor nitpick though: your code is missing a cast of the return value of alloca
. It shouldn’t even compile.