Making alloca more safe

dsimcha dsimcha at yahoo.com
Mon Nov 16 06:42:44 PST 2009


== Quote from Denis Koroskin (2korden at gmail.com)'s article
> On Mon, 16 Nov 2009 17:01:32 +0300, dsimcha <dsimcha at yahoo.com> wrote:
> > == Quote from Walter Bright (newshound1 at digitalmars.com)'s article
> >> Denis Koroskin wrote:
> >> > C standard library alloca function has an undefined behavior when
> >> > requested size is large enough to cause a stack overflow, but many
> >> > (good) implementations return null instead. So does DMD, for example.
> >> I
> >> > believe it would be even better to go ahead and enforce D
> >> implementation
> >> > to return a GC allocated chunk of memory instead of null in that case.
> >> > It will not incur any performance hit in 99.9% of the cases and
> >> prevent
> >> > a bug from being happen in the rest. It will also make writing code
> >> > using it easier (and more safe), since you don't have to worry about
> >> > possible stack overflow/null-dereference.
> >> I'm a little reluctant to do this because alloca is supposed to be a low
> >> level routine, not one that has a dependency on the rather large and
> >> complex gc. 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).
> >> And secondly, I wish to emphasize that a null pointer seg fault is not
> >> an unsafe thing. It does not lead to memory corruption. It simply stops
> >> the program.
> >
> > Yes, but it stops the program in such a way that it's very hard to
> > figure out
> > why/where it died.  The solution, which I've wanted for a while and I
> > think others
> > have proposed, is for DMD to implicitly assert that every pointer is
> > non-null
> > before dereferencing it when in debug mode.
> ... or use the type system to enforce all/most of the pointers to be
> non-null.

Yes, but this would greatly increase the complexity of the type system, which is
already getting too complex.  A simple implicit assert would solve the problem 90%
as well for 10% of the complexity.



More information about the Digitalmars-d mailing list