What exactly does "@safe" mean?

Paulo Pinto pjmlp at progtools.org
Sat Jun 1 14:43:41 PDT 2013


Am 01.06.2013 23:34, schrieb Peter Alexander:
> On Saturday, 1 June 2013 at 21:02:44 UTC, Jonathan M Davis wrote:
>> @safe is for memory safety, meaning that @safe code cannot corrupt
>> memory. You
>> can get segfaults due to null pointers and the like, but you can't
>> have code
>> which writes passed the end of a buffer, or which uses a freed memory,
>> or does
>> anything else which involves writing or reading from memory which
>> variables
>> aren't supposed to have access to.
>
> Not true.
>
> void foo(int* p) @safe
> {
>      *p = 0;
> }
>
> void main()
> {
>      int[3] buf1 = [1, 2, 3];
>      int[1] buf2;
>      int* p = buf2.ptr;
>      --p;
>      foo(p);
>      import std.stdio;
>      writeln(buf1);
> }
>
> For me, this prints [1, 2, 0]. You could easily come up with an example
> which writes to freed memory.
>
> You can argue that foo didn't "cause" this problem (the undefined
> behaviour from the pointer arithmetic in main did), but that's
> irrelevant: what guarantees do I have when I call a @safe function that
> I don't have with any non- at safe function?
>
> Do @safe functions only provide guarantees when the inputs are valid, or
> is it the case the @safe functions are guaranteed to not *introduce* any
> new undefined behaviour?

I always assumed that the role of @safe is to behave like safe code in 
Ada, Modula-3, C#, Oberon family and so on.

No C like tricks are allowed and in certain scenarios one could even 
disallow the linkage of modules not considered safe.

For example in .NET, IIS only allows assemblies with unsafe code if 
configured by the administrator. Unsafe code is also forbidden for Go
packages on App Engine.

--
Paulo


More information about the Digitalmars-d mailing list