logoalt Hacker News

torginusyesterday at 1:43 PM1 replyview on HN

Even the statement that (100% safe) Rust does not have memory bugs/mutable aliasing is not always true.

It's well known that Rust has difficulty representing graph-like memory structures, and people have taken to using arrays of `Node`-s to represent graphs, where each graph edge represents a pointer to another node.

This both efficient, and fast, but this approach sidesteps the borrow checker.

If you had a method that 2 mutable `Node` references as parameters, the borrow checker would complain if they'd point to the same struct. If you pass 2 ints, it won't.

Likewise, since liveness is tracked by user logic, you can refer to stale, deallocated `Node`-s or ones that haven't been initialized yet.

I've had people argue this is not a true memory bug, since you're not causing 'real' memory faults, but in C, `malloc` is just a function that hands you pointers into chunks of pre-allocated memory space most of the time, when it doesn't have to ask the OS for more.

I know from experience some people see this criticism as an attack on their favourite language and instantly rebuke it.

But I'd like to argue that there's something there, and it bears thinking about how 'memory allocation exisitng outside Rust' and 'memory allocating existing inside Rust' behave differently might be seen as an interesting dicothomy that needs to be resolved and that resolution might improve Rust's (or some successor language's) memory model.


Replies

ViewTrick1002yesterday at 7:15 PM

The difference is the checking, and actual enforcement of it.

Go and use get_unchecked if you want to and get C like behavior. But the safety note tells you the potential issues:

Safety

Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.

You can think of this like .get(index).unwrap_unchecked(). It’s UB to call .get_unchecked(len), even if you immediately convert to a pointer. And it’s UB to call .get_unchecked(..len + 1), .get_unchecked(..=len), or similar.

https://doc.rust-lang.org/std/vec/struct.Vec.html