What is the best way to store a pointer as a value of another pointer?
I have a variable ptr
that is of type *mut u8
. How do I store the address that the ptr
points to as the value of another pointer t
that is also of type *mut u8
.
I am trying to do something like
*t = ptr;
I get expected u8, found *-ptr
error. I understand the address ptr
will be 64 bits. I want to fill up 64 bits starting from address t
.
You generally don't want to do that, but I'll trust you know what you're doing.
The key here is to understand a few things:
Box<T>
is roughly equivalent to a*T
allocated on the heap, you can useBox::into_raw
to convert it into a*T
.If you do this, you're effectively leaking the heap allocated
Box<T>
, because Rust no longer knows where it is, or tracks it. You must manually convert it back into a droppable object at some point, for example usingBox::from_raw
.You must
Box::new(...)
a value to ensure it is put on the heap, otherwise your raw pointer will point into the stack, which will eventually become invalid.Mutable aliasing (which means two
&mut T
pointing to the same data) causes undefined behavior. It is extremely important to understand that undefined behavior is not triggered by concurrent writes to mutable aliases... it is triggered by mutable aliases existing at the same time, in any scope....but, if you really want to, you'd do it like this:
Assign one pointer to another:
ptr
is a pointer and the address it points to isNULL
. This value is now stored in the pointert
of the same type asptr
:t
points to the addressNULL
.If you wanted to have
t
be a pointer to the address of another pointer, you would need to take a reference toptr
. The types also could not be the same:Raw pointers have no compiler-enforced lifetimes associated with them. If you want to keep the address of something after the value has disappeared, that's an ideal case for them — you don't have to do anything:
In rarer cases, you might want to store the address in a
usize
(a pointer-sized integer value):It really sounds like you are confused by how pointers work, which is a pretty good sign that you are going to shoot yourself in the foot if you use them. I'd strongly encourage you to solely use references in any important code until your understanding of pointers has increased.