Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust static variables leak memory #2

Closed
DanieleDiBenedetto opened this issue Apr 8, 2020 · 0 comments
Closed

Rust static variables leak memory #2

DanieleDiBenedetto opened this issue Apr 8, 2020 · 0 comments

Comments

@DanieleDiBenedetto
Copy link
Collaborator

DanieleDiBenedetto commented Apr 8, 2020

lazy_static crate offers a way to define a global "static" variable following the execution of a piece of code that is supposed to instantiate a value, as opposed to "constant" variables that don't allow this. The static declared in this way is thread-safe and lasts as much as the entire program; however, when the program ends, the destructor is not called automatically (this feature is not supported by rust), causing a memory leak.
Use static and lazy_static would be the best solution for us, because there is no way to directly instantiate the values we need as constants. Is the memory leak acceptable here ?
If not, there could be other solutions:

  • Use thread_local that has the same functionality of lazy_static except that the scope of the static variable will be only the thread in which it is defined, so in multi-threaded applications we will have the same duplicated static variable for each thread, but the destructor of the variable is run when the program ends;
  • Wrap the constant we need in another struct, and carry this struct around (like a Context), and free it when we don't need it anymore;
  • Using functions that return the constant when it's needed, and drop it immediately after.
@DanieleDiBenedetto DanieleDiBenedetto changed the title lazy_static leaks memory rust static variables leaks memory Apr 8, 2020
@DanieleDiBenedetto DanieleDiBenedetto changed the title rust static variables leaks memory Rust static variables leaks memory Apr 8, 2020
@DanieleDiBenedetto DanieleDiBenedetto changed the title Rust static variables leaks memory Rust static variables leak memory Apr 8, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant