Denis Koroskin wrote:
On Mon, 16 Nov 2009 19:27:41 +0300, Andrei Alexandrescu
<[email protected]> wrote:
bearophile wrote:
Walter Bright:
A person using alloca is expecting stack allocation, and that it
goes away after the function exits. Switching arbitrarily to the gc
will not be detected and may hide a programming error (asking for a
gigantic piece of memory is not anticipated for alloca, and could be
caused by an overflow or logic error in calculating its size).
There's another solution, that I'd like to see more often used in
Phobos: you can add another function to Phobos, let's call it salloca
(safe alloca) that does what Denis Koroskin asks for (it's a very
simple function).
Can't be written. Try it.
Andrei
It's tricky. It can't be written *without a compiler support*, because
it is considered special for a compiler (it always inlines the call to
it). It could be written otherwise.
I was thinking about proposing either an inline keyword in a language
(one that would enforce function inlining, rather than suggesting it to
compiler), or allways inline all the functions that make use of alloca.
Without either of them, it is impossible to create wrappers around
alloca (for example, one that create arrays on stack type-safely and
without casts):
T[] array_alloca(T)(size_t size) { ... }
or one that would return GC-allocated memory when stack allocation fails:
void* salloca(size_t size) {
void* ptr = alloca(size);
if (ptr is null) return (new void[size]).ptr;
return ptr;
}
The problem of salloca is that alloca's memory gets released when
salloca returns.
Andrei