Jack said:
Suppose
int size = INT_MAX / 8;
char a[size];
are declared to use the feature of variable lenght array(VLA) in C99.
With appropriate #includes, when this code is run, segmentation fault
occurs in Red Hat enterprise Linux with 32-bit compiler.
Howver if
char * str = (char *)malloc(INT_MAX);
is declared and run , with appropriate headers, malloc is able to
return INT_MAX bytes.(this is 8 times more than the previous VLA
declaration)
Does this mean that malloc should be preferred over variable length
arrays, for huge memory allocations ?
Does the standard specify any limit regarding the size of VLA.
VLAs are a useless and unsafe feature added by C99, unless you know
they are always going to be very small.
They are a bone thrown to those rabid users of non-standard extensions
like alloca(), who insist that their programs can't possibly survive
the overhead of true memory allocation.
Huh? So you've never measured the performance of malloc before? The
most useful malloc()'s I've ever seen (the ones with best long term
*sustained* performance) are around 50 clocks overhead per call.
Compare that to a stack pointer subtract -- which will cost at most 1
clock of real performance.
Now, I think C99 is full of it for other reasons, so my solution to
this is to commonly write alternative malloc()'s from scratch with all
sorts of functional differences (usually pool based with a "freeall"
function.) Straight C sucks for ADTs, if for no other reason, that the
cost of a malloc per atomic piece is huge. Going to pool based
allocators lets me bring the overhead down to just a few clocks (a
call, a couple of predicted ifs and adds ...) since the overhead of
"free" is amortized over all the atoms -- so this is an acceptable
stand in, but the C standard is of no help here.
In terms of a combination of speed and simplicity, being able to grab
dynamic memory from the stack is far more convenient. You don't need
to call free, so its like garbage collection without any of the
negative effects of it. (Though, it has new problems, like exposing
stack size considerations, as the OP has stepped into.)