What is a fat pointer?

Share

A fat pointer not only points to a particular address, but also stores some information about it, such as the size of the data structure.

In Rust, fat pointers are frequently used to represent slices, which are contiguous sequences of memory elements. A slice fat pointer stores a pointer to the slice's beginning element and length. This information can be used to perform boundary checks and avoid memory problems.

Code example

Let's take a look at a coding implementation to get a better understanding.

struct StrPtr {
ptr: *const u8,
len: usize,
}
fn main() {
let s1 = String::from("I like learning from Educative Answers");
let ptr = s1.as_ptr();
let len = s1.len();
let fatptr = StrPtr { ptr, len };
unsafe {
let slice = std::slice::from_raw_parts(fatptr.ptr, fatptr.len);
let str = std::str::from_utf8_unchecked(slice);
println!("{}", str);
}
}

Code explanation

Let’s understand how the code above works:

  • Lines 1–4: We define a struct with the name of StrPtr to create a fat pointer that stores both the address and length of the pointed value.

  • Lines 7–10: We create an object and store its pointer and length in two variables, and then combine them into a StrPtr struct to create a fat pointer.

  • Lines 11–15: Using the unsafe block, we make a slice from a fat pointer representing a string. It then uses std::str::from_utf8_unchecked to convert the slice to a string, assuming the data is valid by the UTF-8 standard and has no runtime checks. To output the generated string, we use println!.

Copyright ©2024 Educative, Inc. All rights reserved