+Dereferencing a pointer after the lifetime of its target has ended causes undefined behavior. Memory +may be corrupted, causing the program to crash or behave incorrectly, in some cases exposing the program +to potential attacks. +
+ +
+When dereferencing a pointer in unsafe
code, take care that the pointer is still valid
+at the time it is dereferenced. Code may need to be rearranged or changed to extend lifetimes. If
+possible, rewrite the code using safe Rust types to avoid this kind of problem altogether.
+
+In the following example, val
is local to get_pointer
so its lifetime
+ends when that function returns. However, a pointer to val
is returned and dereferenced
+after that lifetime has ended, causing undefined behavior:
+
+One way to fix this is to change the return type of the function from a pointer to a Box
,
+which ensures that the value it points to remains on the heap for the lifetime of the Box
+itself. Note that there is no longer a need for an unsafe
block as the code no longer
+handles pointers directly:
+