Adamish
2 min readApr 23, 2024

The following is my understanding, which may or may not be correct and I'm probably glossing over some things.

Shadowing is just giving up your human "handle" to the data in memory, because you're assigning that "handle" to some other piece of data in memory.

Aside: Thinking about it as assigning a name to a piece of data in memory rather than assigning a value to a variable might help.

I'm not sure it makes a whole lot of sense to worry about whether or not a variable (in actual fact, its data in memory) is "alive" in the current scope. If you have a handle to it (either with a named variable `a` or a pointer to the memory address), then that's what you have. Rust won't prematurely free that memory but if you've given up your "handle", it will still be there.

Now, when the value is dropped (either explicitly using `drop` or when the variable goes out of scope), Rust assumes you're finished with it, and tells the OS/allocator that the memory is no longer required.

That's why it's necessary to make assertions about the pointers after they are dropped in `unsafe` blocks because at any time after Rust marks the memory as free, then the OS can re-allocate it to another process and you may end up with garbage data if you dereference a pointer to that memory address.

In a small piece of code running on a probably under-utilised machine it's not surprising that you still see those original values when you dereference those pointers, but this is literally one of the classes of bugs that Rust will actively work against you to prevent when you try and implement it in your code and forces you to acknowledge that by marking it as `unsafe`:

```

error[E0133]: dereference of raw pointer is unsafe and requires unsafe function or block

--> src/server.rs:60:25

|

60 | assert_eq!({*ptr},5);

| ^^^^ dereference of raw pointer

|

= note: raw pointers may be null, dangling or unaligned; they can violate aliasing rules and cause data races: all of these are undefined behavior

```

Adamish

I’m a Lead Developer and write mostly Ruby on Rails. I also dabble in any language that takes my fancy.