Academy
Slices and Buffer Safety: How Rust Made the Buffer Overflow Extinct
Rust slices (`&[T]` and `&str`) pair a pointer with an explicit length and runtime bounds checking,eliminating buffer overflows while uniting vectors and arrays
6 menit baca
Di halaman ini
The buffer overflow is the cockroach of computer security—it's been around since the 1970s, it's survived every attempt to eradicate it, and it's responsible for more damage than any other single class of vulnerability. The Morris Worm (1988), Code Red (2001), Heartbleed (2014), and countless others—all buffer overflows. All caused by the same fundamental problem: a pointer that doesn't know how much data it's allowed to access.
In C, when you pass an array to a function, you pass a pointer. Just a pointer. The function has no idea how large the array is. It trusts the caller to pass the correct length as a separate parameter. If the caller gets the length wrong—or if an attacker manipulates the length—the function reads or writes past the end of the array, corrupting adjacent memory, leaking secrets, or executing arbitrary code.
Rust's slice type (&[T]) is the definitive solution to this problem. A slice is a fat pointer: it contains both the address of the data AND its length. Every index access is bounds-checked. Every subslice operation verifies the range. Buffer overflows are impossible with slices because the slice knows its own size and refuses to access memory beyond it.
At RantAI, slices are our primary abstraction for working with contiguous data. We pass &[u8] instead of raw byte pointers, &str instead of C strings, and &[Record] instead of pointer-and-length pairs. This article, drawn from Chapter 10 of our guide "The Rust Programming Language," covers slices, string slices, and why they make buffer overflows structurally impossible.
What Is a Slice?#
fn main() {
let data = vec![10, 20, 30, 40, 50];
// A slice is a view into contiguous memory: (pointer, length)
let slice: &[i32] = &data[1..4]; // Elements at index 1, 2, 3
println!("{:?}", slice); // [20, 30, 40]
// The slice knows its length
println!("Length: {}", slice.len()); // 3
// Bounds checking prevents buffer overflows
// println!("{}", slice[5]); // PANIC: index out of bounds
// Safe access with .get()
match slice.get(5) {
Some(val) => println!("Found: {}", val),
None => println!("Index out of bounds"), // This branch executes
}
}
A slice &[T] is two values packed together: a pointer to the first element and a count of elements. This is called a fat pointer—it's twice the size of a regular pointer (16 bytes on 64-bit systems instead of 8), but that extra 8 bytes buys you bounds-checked access to every element.
Slices from Different Sources#
fn sum(data: &[i32]) -> i32 {
data.iter().sum()
}
fn main() {
// From a Vec
let vec = vec![1, 2, 3, 4, 5];
println!("Vec sum: {}", sum(&vec));
// From a fixed-size array
let array = [10, 20, 30];
println!("Array sum: {}", sum(&array));
// From a subrange
println!("Partial sum: {}", sum(&vec[2..]));
// From another slice
let slice = &vec[1..4];
println!("Slice sum: {}", sum(slice));
}
The function sum takes &[i32]—it doesn't care whether the data comes from a Vec, an array, or another slice. This is one of Rust's most powerful abstractions: slices unify access to contiguous memory regardless of the backing storage.
String Slices: &str#
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let sentence = String::from("hello beautiful world");
let word = first_word(&sentence);
println!("First word: {}", word); // "hello"
// &str works with both String and string literals
let literal_word = first_word("goodbye cruel world");
println!("First word: {}", literal_word); // "goodbye"
}
&str is a slice of UTF-8 bytes. Like &[T], it's a fat pointer (pointer + length). Unlike C strings, it doesn't rely on a null terminator—the length is stored explicitly, so string slices can contain null bytes and the length is always known without scanning.
Mutable Slices#
fn double_all(data: &mut [i32]) {
for val in data.iter_mut() {
*val *= 2;
}
}
fn main() {
let mut numbers = vec![1, 2, 3, 4, 5];
double_all(&mut numbers[1..4]); // Double elements at index 1, 2, 3
println!("{:?}", numbers); // [1, 4, 6, 8, 5]
}
&mut [T] provides exclusive mutable access to a contiguous range. The same borrowing rules apply: while a mutable slice exists, no other references to the underlying data can exist.
Why Slices Prevent Buffer Overflows#
In C:
// C: buffer overflow waiting to happen
void process(char* data, int len) {
for (int i = 0; i <= len; i++) { // Off-by-one: <= instead of <
data[i] = toupper(data[i]); // Writes past the buffer on last iteration
}
}
In Rust:
// Rust: buffer overflow is impossible
fn process(data: &mut [u8]) {
for byte in data.iter_mut() { // Iterator respects bounds automatically
byte.make_ascii_uppercase();
}
// Even with indexing, bounds are checked:
// data[data.len()] would panic, not corrupt memory
}
The iterator data.iter_mut() produces exactly data.len() elements—no more, no less. Off-by-one errors in iteration are structurally impossible. Direct indexing is bounds-checked at runtime, converting a potential memory corruption into a controlled panic with a clear error message.
Broader Implications: Slices as Universal Interface#
At RantAI, &[T] is our universal interface for contiguous data. Functions that process arrays take &[T], not &Vec<T> or &[T; N]. This means the same function works with any contiguous data source—vectors, arrays, memory-mapped files, or subranges of any of these. The slice abstraction decouples algorithms from storage.
Practical Applications & Strategic Takeaways#
For newcomers: Accept &[T] in function parameters, not &Vec<T>. Slices are more flexible and work with both vectors and arrays.
For C veterans: Slices are what pointer+length should have been from the start. Same performance, zero buffer overflow risk. The bounds check overhead is negligible—and the compiler often elides it when it can prove the index is in range.
For performance engineers: Use .get() for checked access that returns Option instead of panicking. Use iterators instead of indexing for zero-overhead sequential access.
Our Commitment to Open Knowledge#
RantAI is committed to open education. Slices are covered in Chapter 10 of our guide, "The Rust Programming Language," freely available online.
Explore these concepts further: https://trpl.rantai.dev
Support Our Mission & Get Your Handbook#
Get the Handbook on Amazon KDP: https://www.amazon.com/dp/B0DHCMD3F2
Get the Handbook on Google Play Books: https://play.google.com/store/books/details?id=INwfEQAAQBAJ
Have slices saved you from a buffer overflow that would have happened in C? Share your slice success stories below!
#RustLang #Slices #BufferOverflow #MemorySafety #RantAI #LearnRust #FatPointers #BoundsChecking #StringSlices #SystemsProgramming
Artikel berikutnya
Smart Pointers: Box, Rc, and Arc for Complex Ownership Patterns