Correct use of MaybeUninit with heap-allocated variables?

A copy of code can be found here: Rust Playground

I just want to cache a variable computed at runtime to a static variable so that it is globally accessible (I guarantee that they will not be accessed after dropped) without using lazy_static! or Box<>.

I have been playing around *const S and MaybeUninit<S> for half a day, but I got severe memory-like problems as demonstrated.

Any clues? If possible, I would prefer not to add any extra dependency.

Your first call to read is consuming the String, not a copy or reference, so when it then falls out of scope at the end of consume_var, it's contents are freed. The same raw bytes are still hanging around in STATIC_VAR, but they're no longer representing a pointer to a valid allocation - you're double-freeing, but 10 times instead of only twice.

In particular, see this note in the MaybeUninit::read documentation:

When using multiple copies of the data (by calling read multiple times, or first calling read and then assume_init ), it is your responsibility to ensure that that data may indeed be duplicated.

String cannot be duplicated in this way, because it contains a unique pointer to its contents. (As hinted at by it not being Copy) To get a reference to the static string, and not free it when you're done, use get_ref instead of read.

2 Likes

Works perfectly! Thx!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.