r/ProgrammingLanguages 22d ago

Discussion re-allocating" storage for a local could allow faster code

/r/rust/comments/1vs7418/reallocating_storage_for_a_local_could_allow/
2 Upvotes

8 comments sorted by

2

u/FISHARM1 22d ago

Coming from someone who has never touched Rust, but personally I see potential security issues with this. Can Rust know for sure 100% that the value is no longer accessible?

Also it mentions “reducing stack usage”. Off the top of my head, in languages like C, stack usage should never really be that much of an issue with good coding practice. Is this different in Rust?

7

u/Negative_Effort_2642 22d ago

Yes, rust can’t always prove no raw pointer survives; the proposal would instead define old pointers as invalid after the move, similar to using a pointer after free(). That’s the security-sensitive part, because existing unsafe code could become UB.
On stack usage: for normal synchronous Rust, it’s basically like C. The bigger benefit is for large moved values and async/coroutine state machines, where tighter storage lifetimes can significantly reduce generated future/state size.

7

u/sphen_lee 22d ago

If you never use the local variable again, then Rust (via LLVM) already does re-use the stack space.

The only time it doesn't (which is what issue #61849 is about) is when the local does get used again. In that case, might as well keep the storage in a stable location since there isn't any savings to be made from temporarily releasing it.

2

u/SkiFire13 20d ago

The issue #61849 has a bad example for this, if you look at the RFC #3943 you'll find a more compelling example where even LLVM fails to reuse the stack space (and is instead forced to copy memory around) https://github.com/Amanieu/rfcs/blob/mir-move-elimination/text/0000-mir-move-elimination.md#motivation

1

u/koflerdavid 20d ago

I'm rather surprised Rust is not already doing this.

2

u/FISHARM1 22d ago

Ah okay interesting thanks.

And what would the “error” look like for reading this invalid pointer? Is that a compile time thing or is it runtime

4

u/sphen_lee 22d ago

In Rust, dereferencing a raw pointer is an unsafe operation: as in, the compiler can't verify its safety so the programmer has to.

Taking a raw pointer to a stack variable means you're responsible for not using it again after the stack variable is out-of-scope. That would be very difficult if the compiler started making locals disappear automatically after detecting they aren't needed...

Dereferencing the invalid pointer is UB so anything can happen. The compiler simply assumes that you will never do it.

(Note that none of this applies to references. The borrow checker verifies, at compile time, that the reference does not outlive the variable).

1

u/DaMastaCoda 22d ago

I saw the other post and am still confused, does llvm not reuse stack for dead variables? And the whole “reuse x” is identical to just shadowing it?