-
-
Save rust-play/bb35dc8c6e8582f29e38b09f9c9303d3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
use std::alloc::{alloc, dealloc, Layout}; | |
//use std::fmt::Pointer; | |
fn main() -> () { | |
// Number of elements to allocate | |
const NUM_ELEMENTS: usize = 1024; | |
// Size of each element in bytes | |
const ELEMENT_SIZE: usize = 64; // 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!("{:p} > {:p}", &ptr, ptr); | |
// Use the allocated memory (example: initialize to zero) | |
unsafe { | |
for i in 0..NUM_ELEMENTS { | |
// Accessing elements: | |
for j in 0..ELEMENT_SIZE { | |
if j % 4 == 0 { | |
let element_ptr = ptr.add(i * j) as *mut i32; | |
println!("{:p} > {:p}", &element_ptr, 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