@safe leak fix?

Jason House jason.james.house at gmail.com
Thu Nov 12 15:34:48 PST 2009


Steven Schveighoffer Wrote:

> On Thu, 12 Nov 2009 08:45:36 -0500, Jason House  
> <jason.james.house at gmail.com> wrote:
> 
> > Walter Bright Wrote:
> >
> >> Jason House wrote:
> >> > At a fundamental level, safety isn't about pointers or references to
> >> > stack variables, but rather preventing their escape beyond function
> >> > scope. Scope parameters could be very useful. Scope delegates were
> >> > introduced for a similar reason.
> >>
> >> The problem is, they aren't so easy to prove correct.
> >
> > I understand the general problem with escape analysis, but I've always  
> > thought of scope input as meaning @noescape. That should lead to easy  
> > proofs. If my @noescape input (or slice of an array on the stack) is  
> > passed to a function without @noescape, it's a compile error. That  
> > reduces escape analysis to local verification.
> 
> The problem is cases like this:
> 
> char[] foo()
> {
>    char buf[100];
>    // fill buf
>    return strstr(buf, "hi").dup;
> }
> 
> This function is completely safe, but without full escape analysis the  
> compiler can't tell.  The problem is, you don't know how the outputs of a  
> function are connected to its inputs.  strstr cannot have its parameters  
> marked as scope because it returns them.
> 
> Scope parameters draw a rather conservative line in the sand, and while I  
> think it's a good optimization we can get right now, it's not going to  
> help in every case.  I'm perfectly fine with @safe being conservative and  
> @trusted not, at least the power is still there if you need it.
> 
> -Steve

what's the signature of strstr? Your example really boils down to proving strstr is safe. You're implying that the return of buf from strstr is unsafe. Indeed, my intentionally short post didn't discuss returning from functions. Ignoring that for a moment, surely you'd agree the following is safe:

char[] foo(){
    char[100] buf;
    copystringintobuf(buf, "hi");
    return buf[0..2].dup;
}

As far as return types, there are two subtle issues:
1. Returned input argument must preserve the scope requirements of the caller. A similar problem as return variables and const annotation.
2. Unlike const annotations, there is more than three states for scope, it's simply a measure of how deep/shallowvariables can be in the stack.



More information about the Digitalmars-d mailing list