Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 11, 2025 14:37
Show Gist options
  • Save rust-play/be3425a594b9a5fdfe362f8df7b3ade7 to your computer and use it in GitHub Desktop.
Save rust-play/be3425a594b9a5fdfe362f8df7b3ade7 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::alloc::{alloc, dealloc, Layout};
//use std::fmt::Pointer;
fn main() -> () {
// Number of elements to allocate
const NUM_ELEMENTS: usize = 100;
// Size of each element in bytes
const ELEMENT_SIZE: usize = 8; // Assuming 4 bytes per element (e.g., 32-bit integer)
// Calculate total size in bytes
let total_size = NUM_ELEMENTS * ELEMENT_SIZE;
// Create Layout for allocation
let layout = Layout::from_size_align(total_size, ELEMENT_SIZE).unwrap();
// Allocate memory using alloc()
let ptr = unsafe { alloc(layout) };
// Check if allocation was successful
if ptr.is_null() {
panic!("Allocation failed!");
}
// Print the memory address of the allocated block
println!("Memory address: {:p}", ptr);
// Use the allocated memory (example: initialize to zero)
unsafe {
for i in 0..NUM_ELEMENTS {
// Accessing elements:
let element_ptr = ptr.add(i * ELEMENT_SIZE) as *mut i32;
println!("{:p}", element_ptr);
*element_ptr = 0;
}
}
// Deallocate memory using dealloc()
unsafe { let _ = dealloc(ptr, layout); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment