Re: C99 dynamic array
On Feb 14, 11:39 am, kwikius <a...@servocomm.freeserve.co.uk>
wrote:
On Feb 14, 8:18 am, Ian Collins <ian-n...@hotmail.com> wrote:
kwikius wrote:
On Feb 13, 4:52 am, Jeff Schwab <j...@schwabcenter.com>
wrote:
<C>
#include <stdlib.h>
void f(size_t z) {
<..>
some_type c[z]; // ok in c99 only}
Ah I think I get it. As far as the array is concerned z is
a constant, so it cant resize after its created. Thats
quite neat, if you can grab an arbitrary amount of space
on the stack in a function.
As observed later, it then raises questions about how this
affects optimisations, as you have a runtime constant.
There is also one potentially crippling problem with VLAs:
no indication of failure. You can bugger your stack without
realising.
You can do that very well without VLA's as well. Stack overflow
is undefined behavior in both C and C++.
Another complication is the incompatibility with C caused by
the different interpretation of const,
void f() {
const size_t s = 42;
int bla[s];
}
requires a VLA in C, but not in C++.
My current opinion is:
Looks cool but only on paper. Essentially its a local optimisation,
but in practise gives the optimiser one more extremely heavyweight
variable to deal with, the stack pointer, and so probably causes major
problems in wider optimisations, such as inlining. OTOH I don't know
much about optimisation, but they do seem to run a mile from runtime
constants and especially pointers which this looks likely to create in
abundance.
So in practise I would guess most implementations would end up using
the heap to solve this, unless they are specifically not allowed to,
which apparently isnt the case.
I'm pretty sure that most implementations do allocate on the
stack, at least in simple cases, and probably in more
complicated cases as well. (Remember, the memory has to be
freed if you do a longjmp out of the function.)
Simple cases like these weren't the reason it wasn't adopted
into C++. The fact that you can use a VLA as the last element
of a struct causes problems with inheritance, for example. And
of course, the compiler would have to memorize somewhere how
many times to call the destructor. And sizeof a VLA, or a
struct with a VLA, isn't a constant. It could certainly be made
to work in C++, with enough restrictions. but overall, it would
require some analysis to adapt, and I guess no one felt is was
worth the work.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34