5 comments

[ 4.4 ms ] story [ 29.8 ms ] thread
as someone who's pretty much only written high level languages and doesn't really know what they're talking about, doesn't memory safety generally refer to referencing data you shouldn't (things like buffer overruns?)

please correct me if i'm wrong :)

The exact opposite of that, of course.

Also it includes avoiding use-after-free and avoiding casting to the wrong type.

You might define memory safety to be that if you're accessing an object then (1) that object is actually there, and (2) it's the object you think it is.

I would personally describe memory safety as "all memory accesses to variables are guaranteed to yield a valid value under the type specified by the variable".

So that immediately rules out buffer overflows, use-after-free, double-free, non-atomic data race, dangling pointers, wrong cast, etc.

Some people think memory leaking counts, but I have the same view as Rust. Memory leaking does not corrupt the correctness of a program. And there is no accepted method to universally define "memory leaking" in the first place.

I don't think completely preventing memory leaks at the language level is possible. With reference counting, it's indeed possible to have two objects referring to each other without being referred to from the outside, but even in a garbage collection language like Java, where such objects would eventually be cleaned up, it's still possible to accidentally continue referring to data that you never intend to use again.

There's a lot that languages can do to help manage memory, but the last step will always have to come from the programmer.

At some point you have to start being precise about what you mean by memory leak -- how explicit does your code have to be in how it burns its way through memory? A strictly evaluated functional language (if not a language that lacks dynamic allocation entirely) will have no cycles, but you could still blow through memory with infinite recursion. Suppose you prohibit non-tail-call recursion. You could still write code that grows a list as it executes other logic. But it's hard to do so "accidentally."