Linus with some good observations on garbage collection

bearophile bearophileHUGS at lycos.com
Fri Apr 22 15:38:55 PDT 2011


Iain Buclaw:

> Variable length arrays are just sugary syntax for a call to alloca.

I have an enhancement request in Bugzilla on VLA, with longer discussions. Just two comments:
- It seems alloca() can be implemented with two different semantics: to deallocate at the end of the function or to deallocate at the end of the scope. Usually alloca() deallocates at the end of the function, but that semantic confusion is dangerous. VLA deallocate at the end of the scope, just like any other static array.
- To use alloca you need to use pointers, maybe even slices, it's not DRY, etc. So syntax sugar helps.

In the meantime I've changed my mind a little. Now D I prefer something better than C99 VLAs. I'd like D-VLAs with the same syntax as C99 VLAs but with a safer semantics, closer to this one (but the "alloca" used here must deallocate at the end of the scope):

enum size_t MAX_VLA_SIZE = 1024;
static assert (is(typeof(size) == size_t));
T* ptr = null;
if ((size * T.sizeof) < MAX_VLA_SIZE)
    ptr = cast(T*)alloca(size * T.sizeof);
T[] array = (ptr == null) ? new T[size] : ptr[0 .. size];
array[] = T.init;

This has some advantages: when alloca returns null, or when the array is large, it uses the GC. This allows to both avoid some stack overflows and reduce the risk of the stack memory from becoming too much cold.


> Rather than bore you with the gritty details here, see link:
> http://live.gnome.org/Vala/ReferenceHandling

This is interesting.

Bye,
bearophile


More information about the Digitalmars-d mailing list