Created
November 10, 2023 08:21
-
-
Save ISSOtm/62245fab00bea2bb7357b16333e4d634 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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