Fix misaligned pointer dereference in the buddy example file main.rs
Hello,
my first ever serious merge request
Error
The following error occurred when I ran the cargo run
command on the buddy example located in examples/chapters/chapter12/buddy
:
HEAP starts at 0x5bc20d011061
thread 'main' panicked at src/linked_list.rs:22:9:
misaligned pointer dereference: address must be a multiple of 0x8 but is 0x5bc20d011061
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
Aborted (core dumped)
Reproduction
This error can be reproduced by intentionally misaligning the HEAP
pointer using the offset
method:
// main.rs
// Intentionally misaligning the HEAP Pointer.
fn main() {
println!("HEAP starts at 0x{:x}", unsafe { HEAP.as_ptr().offset(1) as usize });
let mut buddy = unsafe { BuddySystem::<32>::new(HEAP.as_mut_ptr().offset(1) as *mut u8, HEAP_SIZE) };
// ...
}
The use of .offset(1)
should misalign the pointer and cause the crash.
Solution
To solve this, I changed the HEAP
data type in main.rs
from u8
to usize
. Additionally, when passing the pointer to BuddySystem
, it was necessary to cast HEAP.as_mut_ptr()
to *mut u8
. This was a consequence of changing the data type of HEAP
from u8
to usize
:
// main.rs
// Previous Code
static mut HEAP: [u8; HEAP_SIZE] = [0; HEAP_SIZE];
fn main() {
println!("HEAP starts at 0x{:x}", unsafe { HEAP.as_ptr() as usize });
let mut buddy = unsafe { BuddySystem::<32>::new(HEAP.as_mut_ptr(), HEAP_SIZE) };
// ...
}
// Updated Code
static mut HEAP: [usize; HEAP_SIZE] = [0; HEAP_SIZE];
fn main() {
println!("HEAP starts at 0x{:x}", unsafe { HEAP.as_ptr() as usize });
let mut buddy = unsafe { BuddySystem::<32>::new(HEAP.as_mut_ptr() as *mut u8, HEAP_SIZE) };
// ...
}
Using usize
instead of u8
seems to ensure proper memory alignment since usize
is naturally aligned to 8 bytes on 64-bit systems, which prevents the misaligned pointer dereference error we encountered before.
I tested this solution and it worked on my system without any issues. Though, I am not sure whether this is an actual proper solution or rather something like a "quick-fix".
Thank you!