@safe leak fix?

Steven Schveighoffer schveiguy at yahoo.com
Fri Nov 13 05:16:29 PST 2009


On Fri, 13 Nov 2009 07:46:02 -0500, Denis Koroskin <2korden at gmail.com>  
wrote:


>> Sure (with the current compiler):
>>
>> char[] foo()
>> {
>>    char buf[100];
>>    // fill buf
>>    return strstr(buf, "hi"); // no .dup, buf escapes
>> }
>>
>
> No, no, no! It's foo which is unsafe in your example, not strstr!

OK, tell me if foo is now safe or unsafe:

@safe char[] bar(char[] x);

char[] foo()
{
   char buf[100];
   return bar(buf);
}

This is how the compiler looks at the code.  It doesn't know what strstr  
does.  For all it knows, bar (or strstr) could allocate heap data based on  
x and is perfectly safe.

> I don't like his proposal at all. It introduces one more hidden  
> allocation. Why not just write
>
> char[] buf = new char[100];
>
> and disallow taking a slice of static array? (Andrei already hinted this  
> will be disallowed in @safe, if I understood him right).

A major performance gain in D is to use stack-allocated buffers for things  
as opposed to heap-allocated buffers.  The proposal allows lots of  
existing code to be marked as safe without having to add the explicit  
allocations.

I have mixed feelings on the whole thing.  I think disallowing a high  
performance technique such as stack buffer allocation is going to make  
safe code much less attractive, especially when it's very easy to write  
provably safe code that uses stack buffers.  It's going to confuse and  
frustrate developers that want to use such buffers.

The one good thing I see about the proposal is the heap allocations could  
be optimized out later if the compiler can get smarter, without having to  
go remove all those manual heap allocations you added.

The other side of the coin is that you just have to mark your functions as  
@trusted instead of safe.  Then when the compiler gets smarter, you have  
to go back and change those functions to safe.  That's also a possible  
solution.

> Speaking about safety, I don't know how we can allow pointers in safe D:
>
> void foo()
> {
>     int* p = new int;
>     p[1000] = 0; // Will it crash or not? Is this a defined behavior, or  
> not?
>     // If not, this must be disallowed in safe D
> }
>
> And, most importantly, *why* users would want to work with pointers in  
> safe D at all?

I agree with you on this.  But slicing a stack array is not exactly the  
same as taking a pointer and using unbounded pointer arithmetic.  It has  
the potential to escape scope, but not the potential (at least in safe  
mode) of accessing data outside the array.

-Steve



More information about the Digitalmars-d mailing list