Why is life important to slice :: from_raw_parts?

The docs for slice::from_raw_parts warn the programmer about annotating a fragment with the correct lifetime. I suggest that, given some of 'a life, I can accomplish this annotation with

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

I also assume that

  • Since myslice is a link, it has nothing to do with distributing / freeing the underlying data ptr points to. Lifetime annotations do not affect data memory management.
  • There is nothing complicated in managing memory for myslice itself (i.e. a structure containing a pointer and size). It is just like any other structure or i32 . If I put it in a Box , then the std::raw::slice structure will be freed when Box dies. Of course, the data mentioned by the slice will not be released. Lifetime does not affect memory management for the slice.

Why is it important that life is right? Is using the day after tomorrow the only danger for setting the cut time for a slice?

+8
rust lifetime ffi
source share
2 answers

Use-after-free is not the only danger. With the wrong lifetime, you can cause variable smoothing. Take this (contrived) function as an example:

 fn duplicate_mut_slice<'a, T>(xs: &mut [T]) -> &'a mut [T] { let ptr = xs.as_mut_ptr(); // btw, this part is safe! unsafe { std::slice::from_raw_parts_mut(ptr, xs.len()) } } 

Due to how life lines are built, challenges like this will succeed:

 fn alias_first_element<T>(xs: &mut [T]) -> (&mut T, &mut T) { let a = duplicate_mut_slice(xs); let b = duplicate_mut_slice(xs); (&mut a[0], &mut b[0]) } 

Note that in this second function signature, the lifetimes are correct, and using the day after tomorrow is not a (immediate) danger. But mutable smoothing is very insidious. Basically, everything depends on the guaranteed absence of variable smoothing to prevent problems such as race conditions, iterator invalidity, logical errors and, indeed, useless (something controlled by T ). You can cause almost any problem that is possible with a mutable alias.

+9
source share

UPDATE: as stated in delnan, mutable anti-aliasing is a real problem that can result from setting the wrong lifetime. See His / her answer for more details.

Old answer

Use-after-free is really the only danger when setting the slice lifetime. The compiler will trust you and accept the data specified in the slice of life, if you specify the service life. If your annotated lifetime is longer than the real lifetime of the underlying data, you may get errors after use (you can use the slice while the data is already released).

As for your assumptions, they are correct. Lifetime annotations do not affect in-memory data management.

0
source share

All Articles