Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the lifetime important for slice::from_raw_parts?

Tags:

The docs for slice::from_raw_parts warn the programmer to annotate the slice with the correct lifetime. I assume that, given some lifetime 'a, I can perform this annotation with

let myslice: &'a mut [i32] = std::slice::from_raw_parts_mut(ptr, sz)

I also assume that

  • Since myslice is a reference, it has nothing to do with the allocation/deallocation of the underlying data pointed to by ptr. The lifetime annotation doesn't affect the memory management of the data.
  • There's nothing tricky about memory management for myslice itself (i.e. a struct containing a pointer and a size). It's just like any other struct or i32. If I put it in a Box, then the std::raw::slice struct will get deallocated when the Box dies. The data referred to by the slice will not get deallocated, of course. The lifetime doesn't affect the memory management for the slice.

Why is it important that I get the lifetime correct? Is use-after-free the only danger to fear when setting the slice lifetime?