Please explain what you mean by "safe" in this context.
Edit: you may answer: "use alloca then". But the syntax for alloca is not that convenient, and the semantics are very different. A common use for VLA is to declare a temporary array inside the body of a loop, this is not possible with alloca.
My problem is this:
void f(int n)
{
float t[n];
// what do I write here to check if everything is OK ?
...
}Allocating a non-VLA is not safe. Your running program's char x[4096] could go spectacularly wrong.
This is a tiny size, and it would never pose a problem. I'm talking about allocating a few high-resolution video frames on a VLA for temporary computation. It is extremely natural to declare these temporary space inside a for loop as
for (...)
{
float frame[3*width*height]; // temporary data
...
}
but due to the "unsafety" of the VLA implementation it is not very portable. To make it safe in my linux computer I just set "ulimit -s" to a huge value and it works. But it is not very practical to distribute such code to others.Cribbed from some Unix programmer's epitaph.
That doesn't mean that they're not safe, so long as the program reliably terminates[1]. And you can catch stack overflow, it's just not easy, and made especially difficult from a software architecture perspective because neither C nor POSIX support per-thread signal handlers, so catching stack overflow requires cooperation across components and libraries. (Fortunately, POSIX does provide per-thread signal stacks via sigaltstack(2). And I suppose it should be possible to write a shared library that interposes pthread_create and signal/sigaction to support per-thread signal handlers.)
TL;DR: VLAs are fine if you're doing something you might otherwise be doing in FORTRAN. Otherwise, just don't. It's trivial to use GNU obstacks or to write your own, as I do. Just don't go down the rabbit whole of trying to solve all allocation needs; it's not a solvable problem.
[1] Sadly, before Stack Clash was published neither GCC nor clang/LLVM did this :(
Reason? Several security exploits.