Estimate project
← All posts

Deliberately leaking memory in Rust

A look at intentional memory leaks in Rust: why the leak method exists on smart pointers such as Box and when it is worth using.

8 min read
RustMemory ManagementMemory LeakMemory

In this post we will look at memory management and at how Rust lets you ‘leak’ memory intentionally. I am fairly new to the Rust ecosystem, and when I noticed that a smart pointer type like Box comes with a method called leak, I became curious about why it exists and what it is good for. These mechanisms touch on many other topics and use cases, so get comfortable and keep reading. Hopefully it won’t turn out too long.

Leak is not really leaking memory, or is it?

If, like me, you do not come from systems programming, you probably associate the term leaking memory with the JVM or other managed environments such as .NET, where leaks typically happen because of unintended references that stop the garbage collector from reclaiming memory that is no longer used.

With Box::leak in Rust, nothing really leaks; we simply convert a Box<T> on purpose into a static mutable reference &'static mut T, which stops whatever the Box manages from ever being deallocated.

Since we turn it into a reference that can no longer be deallocated, we have in a sense leaked the memory, much as in other languages. The only difference is intent: we did it deliberately, while ordinary memory leaks are unwanted because they can needlessly eat up system resources.

Box::leak usage examples

While researching the subject, I came across a few interesting ways to use this method. The first concerns sharing configuration data throughout your application.

Global config example

use once_cell::sync::OnceCell;

static GLOBAL_CONFIG: OnceCell<&'static AppConfig> = OnceCell::new();

#[derive(Debug)]
struct AppConfig {
   database_url: String,
   app_mode: String,
}

impl AppConfig {
   // Simulates loading a configuration
   fn load() -> Self {
       AppConfig {
           database_url: "https://example.com/mydb".to_string(),
           app_mode: "production".to_string(),
       }
   }
}

fn setup_global_config() {
   let config = Box::new(AppConfig::load());
   let static_ref = Box::leak(config); // Leak the Box to get a static reference
   GLOBAL_CONFIG.set(static_ref).expect("Failed to set global configuration");
}

fn main() {
   setup_global_config();

   // Access the global configuration
   if let Some(config) = GLOBAL_CONFIG.get() {
       println!("Database URL: {}", config.database_url);
       println!("App Mode: {}", config.app_mode);
   }
}

Suppose your application has to reach some data kept in AppConfig for as long as it runs. You can achieve this by putting the config on the heap with the usual Box::new and then leaking it, which turns it into a static mutable reference that we hand over to OnceCell. The AppConfig fields are then accessible just as with any regular instance of this type. This approach works especially well for read-only data that is set once and then read often all over the application.

Note on OnceCell

The OnceCell type comes from the utility crate once_cell and lets you create values that are initialised exactly once. After creation it cannot be modified, but it gives you a safe and efficient way of handling immutable values and postponing initialization until it is needed.

OnceCell comes in several flavours:

  • OnceCell<T>: a value that is set once, usually for lazy initialization (as in the example above).
  • Lazy<T>: a wrapper around OnceCell for values that are lazily initialised the first time they are accessed.
  • OnceCell exists in both sync and unsync versions.

Using OnceCell the classical way:

use once_cell::unsync::OnceCell;

fn main() {
   let cell = OnceCell::new();

   // Set the value
   cell.set(42).expect("Value has already been set");

   // Access the value
   if let Some(value) = cell.get() {
       println!("The value is: {}", value);
   }

   // Trying to set the value again will result in an error
   assert!(cell.set(100).is_err());
}

Example with Lazy:

use once_cell::sync::Lazy;

// Lazily initialize a static value
static CONFIG: Lazy<String> = Lazy::new(|| {
   println!("Initializing configuration...");
   "Config data".to_string()
});

fn main() {
   // The closure is only executed once, on the first access
   println!("CONFIG: {}", *CONFIG);
   println!("CONFIG: {}", *CONFIG); // The closure will not run again
}

You might be asking yourself now why our global config example uses Box::leak rather than Lazy. What sets them apart is that Lazy can only be initialized with compile-time closures and cannot deal with runtime dependencies. When your program builds up a complex data structure while it runs and you later want to share it as a static variable, your best bet is to wrap it in a Box and leak it into a static mutable reference.

Initialization that is thread safe:

use once_cell::sync::OnceCell;
use std::thread;

static GLOBAL_CONFIG: OnceCell<String> = OnceCell::new();

fn main() {
   let handle = thread::spawn(|| {
       GLOBAL_CONFIG.set("Config set by thread".to_string()).unwrap();
   });

   handle.join().unwrap();

   println!("Global config: {}", GLOBAL_CONFIG.get().unwrap());
}

Speaking of threads, I already noted that OnceCell exists in sync and unsync versions, but keep in mind that the sync version only helps during initialization: it guarantees that the code in the given closure runs exactly once at initialization, even when multiple threads are involved. Lazy, on the other hand, does nothing to coordinate concurrent access to the stored value, so in a multithreaded setting you have to handle that yourself. In our example this is easy to fix with a Mutex, e.g.,:

use once_cell::sync::Lazy;
use std::sync::Mutex;

struct MySingleton {
   // Example fields
   pub data: String,
}

// Global singleton instance
static SINGLETON: Lazy<Mutex<MySingleton>> = Lazy::new(|| {
   Mutex::new(MySingleton {
       data: "Initial data".to_string(),
   })
});

fn main() {
   // Access the singleton
   let singleton = SINGLETON.lock().unwrap();
   println!("Singleton data: {}", singleton.data);
}

Since we are discussing OnceCell, it is worth pointing out another option from std::sync, called Once. Conceptually it resembles OnceCell, but unlike OnceCell it holds no value. Once lets us run a given closure a single time, yet gives no access to what it produced. That limitation can of course be worked around with a static mutable variable, e.g.,:

use std::sync::Once;

static INIT: Once = Once::new();
static mut VALUE: Option<String> = None;

fn main() {
   unsafe {
       INIT.call_once(|| {
           VALUE = Some("Hello, world!".to_string());
       });
       println!("{}", VALUE.as_ref().unwrap());
   }
}

As you can probably guess by now, Box::leak is useful any time something has to stay available for the entire run of the program and you need a guarantee that the data will not be freed too early. It suits config data that is initialized once and then read, but you can also use it to keep a global piece of data that you will modify later. That comes in handy for things like a job queue or a logging system, e.g.,:

struct JobQueue {
   jobs: Vec<String>,
}

impl JobQueue {
   // Creates a new JobQueue
   fn new() -> Self {
       JobQueue {
           jobs: Vec::new(),
       }
   }

   // Adds a job to the JobQueue
   fn add_job(&mut self, job: String) {
       self.jobs.push(job);
   }

   // Displays all jobs in the queue
   fn display_jobs(&self) {
       for job in &self.jobs {
           println!("{}", job);
       }
   }
}

fn initialize_job_queue() -> &'static JobQueue {
   let queue = Box::new(JobQueue::new());
   Box::leak(queue)
}

fn main() {
   let queue = initialize_job_queue();

   // Add some jobs to the queue
   unsafe {
       let queue_mut = queue as *const JobQueue as *mut JobQueue;
       (*queue_mut).add_job("Job 1".to_string());
       (*queue_mut).add_job("Job 2".to_string());
   }

   // Display the jobs
   queue.display_jobs();
}

Box::leak also helps when you want to build a simple callback mechanism. Rather than leaking one piece of data, we leak the whole closure, as shown below:

use std::thread;

fn setup_callback<F: FnOnce() + Send + 'static>(f: F) {
   thread::spawn(move || {
       // Simulate doing some work...
       f(); // Execute the callback
   });
}

fn main() {
   let my_data = Box::new(|| println!("This is a callback!"));
   let static_callback = Box::leak(my_data);
   setup_callback(*static_callback);
}

Leaking memory beyond Box::leak

Apart from the familiar Box::leak, Rust offers a few more ways to hack memory. These hacks are likewise controlled and deliberate, and in how they behave they are closely related to Box::leak.

Rc::into_raw and Arc::into_raw

These two are also somewhat unusual, at least from my point of view. The into_raw functions turn reference counted or atomic reference counted pointers into raw pointers. Raw pointers work much like pointers in C and C++ and give direct access to memory, bypassing the borrowing rules Rust normally enforces. This is handy when interacting with C code and passing ownership of such structures to it. When needed, you can explicitly take the memory back and turn the raw pointers into Rc/Arc again, e.g.,:

use std::rc::Rc;

fn main() {
   let data: Rc<i32> = Rc::new(123);
   let raw: *const i32 = Rc::into_raw(data);

   // Later, convert back to an Rc to avoid memory leak
   unsafe {
       let reconstructed = Rc::from_raw(raw);
       println!("{}", *reconstructed);
       // Rc is dropped here, and memory is deallocated
   }
}

std::mem and std::ptr

Finally, since we are talking about interfacing with C, std::mem and std::ptr deserve a mention. These modules let you allocate, free and modify memory however you like, much as in C/C++. You must, however, be very careful not to genuinely leak memory by accident and keep an eye out for undefined behavior.

use std::ptr;

fn main() {
   unsafe {
       let layout = std::alloc::Layout::from_size_align(1024, 1).unwrap();
       let buffer = std::alloc::alloc(layout);
       ptr::write(buffer, 42u8);  // Example write
       println!("{}", *buffer);

       // Manually deallocate if needed, or "leak" by never deallocating
       std::alloc::dealloc(buffer, layout);
   }
}

Real data leaking in Rust

You may now be wondering whether Box::leak can cause a real memory leak in Rust, and the answer is yes. Take a look at this example:

use std::thread;

fn main() {
   thread::spawn(|| {
       let leaked_data: &'static str = Box::leak(Box::new(String::from("I leak!")));
       println!("{}", leaked_data);
   })
       .join()
       .unwrap();
}

When this runs, the String “I leak!” is allocated on the heap and leaked into static memory via Box::leak. The resulting reference to that static memory exists only for as long as the thread spawned from the main thread lives, and it becomes unreachable once the reference is dropped (when the thread completes on join). As a result, the data outlives the thread, but there is no longer any way to reach it.

The key point is that Box::leak merely changed who owns the data we put on the heap with Box::new. The data physically stays on the heap, but it now has a 'static lifetime and cannot be reclaimed before the program terminates, which means we have a genuine memory leak.