Rust

Rust

Made by DeepSource

Transmute from float or char to reference or pointer RS-E1029

Bug risk
Major

In Rust, the transmute function is used to reinterpret the bits of a value of one type as another type. Hence, both types must have the same size.

Compilation will fail if this is not guaranteed. Transmute is semantically equivalent to a bitwise move of one type into another. It copies the bits from the source value into the destination value.

Hence transmuting from float or char type to reference or pointers is considered bad in Rust because it can lead to undefined behavior. For example, transmuting a float to a pointer can lead to a null pointer exception.

Bad practice

fn main() {
    let x = 3.14;
    let y: *const f32 = unsafe { std::mem::transmute(x) };
    println!("{:?}", y);
    let c = '3';
    let h: *const char = unsafe { std::mem::transmute(c) };
    println!("{:?}", h);
}