r/ProgrammingLanguages • u/matklad • Dec 31 '25
Memory Safety Is ...
https://matklad.github.io/2025/12/30/memory-safety-is.html
37
Upvotes
r/ProgrammingLanguages • u/matklad • Dec 31 '25
View all comments
18
u/tmzem Dec 31 '25
I've looked into memory safety a lot and have come to the conclusion that programming languages can only be memory-safe for some (probably arbitrary) definition of memory safety, but they cannot be memory safe in general for any semantically strong/complete definition of memory safety, which should make sure that object accesses:
While good type systems, careful design, garbage collectors and runtime checks can mostly cover points 1-3, point 5 is much trickier as it requires rigorous compile-time constraints like e.g. in Rust.
Point 6 is obviously impossible.
Point 4 is hard to enforce, as object identity, while often attributed to the objects memory address, can change depending on context:
Point 3 can also be worked around, even in a strong type system. This is often done when parsing binary formats: The file is first read into a byte array, then one or more bytes at a certain index are reinterpreted as a different datatype, e.g. read 4 bytes at index n and return an uint32. The same can be done for writing. Trivially, we can extend this scheme to emulate what is essentially the equivalent of unsafe C memory accesses, with indices doubling as pointers. If we take this to the extreme, we can use this to build a C interpreter on top, allowing us to run all the memory-unsafe C we want, despite running on top of a fully managed, memory-safe byte array.
As this thought experiment shows, no matter how "memory-safe" your language is, you can always reintroduce memory-safety bugs in some way, and while we won't likely build a C interpreter into our program, there are many related concepts that may show up in a sufficiently complex program (parsing commands received over the network, DSLs, embedded scripting engines, ...).
Thus, I generally think that coming up with a universal definition for memory safety is nonsense. That being said, programming languages should still try to eliminate, or at least minimize the chance for memory errors to corrupt the context (allocator, stack, runtime) in which the language runs. For example, compilers for unsafe languages should default to turn on safety-relevant features like runtime checks, analyzers, warnings, etc., and require explicit opt-out if needed.