Safety, undefined behavior, @safe, @trusted

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 5 13:31:04 PST 2009


On Thu, 05 Nov 2009 15:19:46 -0500, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> Steven Schveighoffer wrote:
>> Care to define some rules for "undefined behavior?"
>
> My list may be of help.

Thanks, I found it.

I note that you specify "No escape of a pointer or reference to a local  
variable outside its scope"  There are definitely different degrees of  
detecting this.

 From reading some of your other posts, I take it you mean:
  * you cannot pass such a pointer to another function except by reference
  * you cannot return such a reference or pointer
  * you cannot take the address of a 'ref' parameter, because that  
parameter could be allocated on the stack.

Without doing full escape-analysis, there are some problems with this.   
For example, let's take the function std.string.split.  It takes a  
reference to data and returns a reference to that same data.  However, the  
compiler is unaware of where the data being returned comes from.

For example:

char[] getFirstWordOfFile()
{
char buf[1024];
auto x = buf[0..readFile("foo.d", buf)];
return split(x)[0]; // memory escape
}

I'm not a phobos guy, so I don't know exactly how to do readFile, but I  
think we all know what it means.

readFile will obviously be marked as @trusted, since it does not escape  
any memory, but calls a (potentially) unsafe C function (read).

But what about split?  Should it be illegal to pass in the reference to  
the stack memory?  Should it be illegal to mark the split function as  
safe?  How does safeD prevent this mistake?

My point is, because without full analysis, the compiler cannot connect  
the outputs of a function with its inputs, only functions which  
heap-allocate defensively, or don't use references, can be marked as  
safe.  Because safety is sometimes contextual, it will be impossible to  
use the all-or-nothing @safe marker on many functions (such as split).

I'm still not sure how to solve this, or whether it will have a large  
impact on how safed works.

-Steve



More information about the Digitalmars-d mailing list