Why is "delete" unsafe?

Paul Backus snarwin at gmail.com
Wed Sep 23 23:06:50 UTC 2020


On Wednesday, 23 September 2020 at 04:15:51 UTC, mw wrote:
> On Saturday, 27 October 2012 at 01:08:12 UTC, Jonathan M Davis 
> wrote:
>> Yes. But using core.memory.GC.free is unsafe for the same 
>> reasons that delete is. It's just that it's a druntime 
>> function instead of a part of the language, so it's less 
>> likely for someone to free GC memory without knowing what 
>> they're doing. It's there because there _are_ times when it 
>> makes sense and is useful, but it's definitely not safe, so 
>> you have to be careful and know what you're doing.
>
> What do you mean by saying "it's definitely not safe" here?
>
> I mean: if I'm careful and know what I'm doing, e.g. remove all 
> the reference to  any part of the `object` before call 
> core.memory.GC.free(object), is there still any inherit 
> "unsafe" side of `free` I should be aware of?
>
> FYI: I just described my use case here:
>
> https://forum.dlang.org/post/hzryuifoixwwywwifwbz@forum.dlang.org

The logic is: @safe code isn't allowed to have access to dangling 
pointers, because you're allowed to dereference pointers in @safe 
code, and dereferencing a dangling pointer is undefined behavior. 
Since manually freeing memory can create dangling pointers, 
you're not allowed to do it in @safe code.

If you can prove with 100% certainty that you're not going to 
create a dangling pointer, you can wrap the call to `free` in a 
@trusted lambda:

     () @trusted { free(ptr); ptr = null; }();


More information about the Digitalmars-d-learn mailing list