DEV Community

Linlee
Linlee

Posted on

Find memory address in Rust

This code demonstrates a few concepts: variable declaration, value printing, converting a numeric value to its byte representation, iteration with enumeration, and printing memory addresses.

Image description

fn main() {
    // convert and find address
    let x: u32 = 32;
    println!("The Value of x is:{}",x);

    // Convert x to bytes and print each byte
    let bytes = x.to_ne_bytes(); // Covert to native endian bytes order
    for (i, byte) in bytes.iter().enumerate(){
        println!("Byte {} of x: {:08b}", i , byte);

    }

    println!("The address of x is: {:p}" ,&x);
    println!("The address of x is: {:p}", &x as *const u32);
    println!("The address of x is: {:p}", &x as *const _);

}
Enter fullscreen mode Exit fullscreen mode

Converting to Bytes and Iteration:

let bytes = x.to_ne_bytes(); // Convert to native endian bytes order

The to_ne_bytes method converts the integer x into an array of bytes in the native endian order of the machine (either little or big endian, depending on the architecture).

for (i, byte) in bytes.iter().enumerate(){
    println!("Byte {} of x: {:08b}", i , byte);
} 
Enter fullscreen mode Exit fullscreen mode

This loop iterates over the byte array. The enumerate method adds a counter (i), and for each byte in bytes, it prints the byte's index and its binary representation (:08b formats the byte as an 8-bit binary number).

Printing Memory Addresses:

println!("The address of x is: {:p}" ,&x);

This prints the memory address of x. The :p formatter is used for pointer types, and &x takes the address of x.

println!("The address of x is: {:p}", &x as *const u32);

This is similar to the previous line but explicitly casts the reference &x to a constant pointer type *const u32.

println!("The address of x is: {:p}", &x as *const _);

This line also prints the address of x, but uses type inference (_) for the pointer type. It's essentially saying "treat &x as a constant pointer to some type, but I don't care to specify what that type is."

The result:

The Value of x is:32
Byte 0 of x: 00100000
Byte 1 of x: 00000000
Byte 2 of x: 00000000
Byte 3 of x: 00000000
The address of x is: 0x16db4e474
The address of x is: 0x16db4e474
The address of x is: 0x16db4e474
Enter fullscreen mode Exit fullscreen mode

Top comments (0)