Walter Bright wrote:
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.

Cyclone has this neat notion that a pointer is associated to a memory "region" (by default, there are 3 regions: the data segment, the heap and the stack of the current function, but you can have user-defined regions). In this case, the function "foo" would have the type:

        @region (`R) T[] foo (@region (`R) T[] a)

where `R is an abstract region name meaning that the return value is in the same region as the argument. When compiling "bar", the compiler would then be able to see that it is returning a pointer to bar's stack region and refuse.

                Jerome
--
mailto:jeber...@free.fr
http://jeberger.free.fr
Jabber: jeber...@jabber.fr

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to