memory safety checks and trust
Steven Schveighoffer
schveiguy at gmail.com
Tue Apr 14 17:16:53 UTC 2020
On 4/14/20 6:08 AM, Walter Bright wrote:
> On 4/13/2020 5:25 AM, Steven Schveighoffer wrote:
>> For instance:
>>
>> void foo()
>> {
>> int*[] b;
>> int a;
>> b ~= &a;
>> // use b but don't expose it outside foo
>> }
>>
>> There are no memory safety violations there.
>> The first case is highly useful, as one often needs scratch space to
>> perform complex calculations or graph algorithms. I see no reason to
>> disallow it.
>
> I see a reason:
>
> void foo()
> {
> int*[1] b = void;
> int a;
> b[0] = &a;
> }
The toy cases aren't real cases, they just show the error and that the
usage is safe.
We are not trying to solve the toy. Of course, adding one element to an
array and doing nothing is not the real case. I'm talking about maybe an
array of millions of pointers, some of which are on the stack (consider
like a linked list where you store the head on the stack), and ensuring
the array doesn't escape the function.
>
> It's faster, too. And if it is written as:
>
> &safe void foo()
> {
> int a;
> int*[1] b;
> b[0] = &a;
> }
>
> it's even @safe (with -preview=dip1000).
>
> I know, I know, this isn't the real use case. But I've done plenty of
> "use scratch data structures on the stack" programming for speed and I
> know how to make it work without needing to store addresses in GC objects.
It's not about knowing how to do it other ways, or doing it the fastest
way. It's about knowing how to do it correctly *this* way. Maybe I don't
want to deal with having to ensure things are freed properly. What if my
graph algorithm has cycles, will RAII (e.g. RefCounted) take care of
that? If you do it right with the GC, then there are no memory issues,
why is the compiler stopping that in @system code? @system is supposed
to be "I know what I am doing".
The answer to "why won't @system let me write this memory safe code?"
shouldn't be "you're doing it wrong". That's factually incorrect, and
the compiler shouldn't bug me about it. Especially when it's trivially
circumvented. @safe is for compiler checks for safety.
That being said, I agree with the simple case of returning a pointer
from a stack variable directly from a function being disallowed. That
also can be easily worked around, which should probably be required, but
is never correct anyway.
-Steve
More information about the Digitalmars-d
mailing list