Hacker News new | ask | show | jobs
by olvy0 881 days ago
It's been a while since I've programmed in Rust, and I was initially surprised that the get() call returned garbage. Could anyone explain why that is? I mostly program in C++ and C#.

After thinking about it, my intuition is that:

- the Vec was passed by value to the function, which in Rust means something different than passing a std::vector in c++ to a function, due to...

- Due to the language semantics, its reference counter remained 1 while inside the function, but decreased to 0 when returning to main, since in Rust if it isn't a borrow (ref) then it's a "steal" - the callee "steals" the Vec completely from the caller. Or something like that.

- Since the reference counter is 0 when returning to main, the Vec is released, akin to calling its destructor if this was C++.

- SOMETHING changed the value of either the internal pointer to the heap inside the stack-allocated Vec (so now it points to garbage), OR something overwrote the Vec's content with some garbage. I'm not sure what that something is, and why would it do that.

I apologize if my explanation/intuition above is garbage in itself, like I said it's been a while since I programmed in Rust.

Edit: formatting

1 comments

You're mostly correct, it is moved into the function (pass by value), and then, at the end of the function's scope, the destructor is called automatically (as the compiler inserts a call to `drop()` at the end of the function) which de-allocates the vec, causing the reference obtained in `main()` become a dangling pointer.
Thank you!
An alternative, more correct but less interesting, explanation: you really need to look at the disassembly (with your specific build of the Rust compiler with the same flags) to see what's really happening. This is why UB (undefined behavior) is dangerous.

For example, the compiler could decide that the entire allocation is unnecessary and elide it, if it's known that the Vec is very small. The compiler could also decide to pass it by ref. Remember that the compiler merely has to preserve your intent, beyond that it is allowed to do whatever it pleases.

https://rust.godbolt.org/