Hacker News new | ask | show | jobs
by syn_rst 2803 days ago
Like this:

  fn leak() {
      // Create a 1KiB heap-allocated vector
      let b = Box::new(vec![0u8; 1024]);
      // Turn it into a raw pointer
      let p = Box::into_raw(b);
      // Then leak the pointer
  }
Obviously that's kind of blatant, but there are more subtle ways to leak memory. Memory leaks aren't considered unsafe, so even though they're undesirable the compiler doesn't guarantee you won't have any.

Reference cycles when using Rc<T> are a big one, but generally it's pretty hard to cause leaks by accident. I've only run into one instance of leaking memory outside of unsafe code, and that was caused by a library issue.

1 comments

The most obvious ways to leak are calling `Box::leak` which is also a very useful API and `mem::forget` (the latter is mostly useful for working with unsafe code).