@safe leak fix?

Michel Fortin michel.fortin at michelf.com
Wed Nov 11 14:00:25 PST 2009


On 2009-11-11 16:47:10 -0500, Walter Bright <newshound1 at digitalmars.com> said:

> Consider the code:
> 
>    @safe:
>      T[] foo(T[] a) { return a; }
> 
>      T[] bar()
>      {
>          T[10] x;
>          return foo(x);
>      }
> 
> Now we've got an escaping reference to bar's stack. This is not memory 
> safe. But giving up slices is a heavy burden.
> 
> So it occurred to me that the same solution for closures can be used 
> here. If the address is taken of a stack variable in a safe function, 
> that variable is instead allocated on the heap. If a more advanced 
> compiler could prove that the address does not escape, it could be put 
> back on the stack.
> 
> The code will be a little slower, but it will be memory safe. This 
> change wouldn't be done in trusted or unsafe functions.

Interesting. This is exactly what I've proposed a few months ago while 
we were endlessly discussing about scope as a function argument 
modifier: automatic heap allocation of all escaping variables.

Of course I'm all for it. :-)

But now you should consider wether or not it should do the same in 
unsafe D. If it doesn't do the same unsafe D will crash for things safe 
D won't crash. If you do this in unsafe D you need a way to force a 
variable not be heap allocated whatever happens. (Perhaps using 'scope' 
as a storage modifier for variables.)

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list