Prototype of Ownership/Borrowing System for D

mipri mipri at minimaltype.com
Wed Nov 20 18:52:12 UTC 2019


On Wednesday, 20 November 2019 at 18:32:42 UTC, IGotD- wrote:
> On Wednesday, 20 November 2019 at 06:57:55 UTC, mipri wrote:
>>
>>   void main() {
>>       auto p = cast(Person*)malloc(Person.sizeof + 10);
>>       birthday(p);
>>       p.name.ptr[0] = 'B';
>>       writeln(p);
>>   }
>>
>
> If you would make main @live, would the compiler automatically 
> put in a call to free for variable 'p' at the end of main?

How I read it is that @live doesn't know anything about malloc or
free (except what it knows by their signatures: that malloc 
returns
a pointer and that free takes ownership of a pointer). A glance
through the commits seems to support this; I don't see references
to either function outside of unit tests, and the docs mention 
that
there's no protection against using the wrong allocator for a
pointer, like free_allocator2(malloc_allocator1());

This compiles without error, for example:

   import std;
   import core.stdc.stdlib: malloc;

   struct Person {
       uint age;
       uint karma;
       char[0] name;
   }

   @live void birthday(scope Person* p) {
       p.age++;
   }

   void consume(Person* p) { }

   @live void main() {
       auto p = cast(Person*)malloc(Person.sizeof + 10);
       birthday(p);
       writeln(p.age);
       consume(p);
   }

Where valgrind points out the use of undefined memory and the
leaked memory. @live just cares that consume() took ownership of
the pointer, even if consume() is not a responsible owner.

Of course you get an error if you try to add @live to consume().

@live isn't a superset of @safe either, since it permits the cast.



More information about the Digitalmars-d mailing list