Skip to content

Instantly share code, notes, and snippets.

@ISSOtm
Created November 10, 2023 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ISSOtm/62245fab00bea2bb7357b16333e4d634 to your computer and use it in GitHub Desktop.
Save ISSOtm/62245fab00bea2bb7357b16333e4d634 to your computer and use it in GitHub Desktop.
// Note: requires Nightly Rust as of 2023-11-03.
use std::alloc::{Allocator, System};
/// Object allowing access to the system allocator.
static SYSTEM: System = System;
fn main() {
let layout = Layout::from_size_align(2, 1).unwrap();
let bytes = SYSTEM.allocate_zeroed(); // `malloc` can return NULL, but this is wrapped as a `Result<NonNull<[u8]>, _>`.
let bytes_ref = unsafe { bytes.as_ref() }; // SAFETY: init'd to all zeros, aligned, and we're dropping this before dealloc.
println!("{}", bytes_ref[0]);
drop(bytes_ref);
unsafe { SYSTEM.deallocate(bytes, layout); } // SAFETY: no refs are still live.
}
fn main() {
let buf = oops();
println!("{}", buf[0]);
print(&buf[0]);
}
fn oops() -> &[u8; 2] {
[0; 2]
}
fn print(what: &u8) {
println!("{}", *what);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment