Skip to content

Messing around with allocations #68

@abgros

Description

@abgros

What will this do?

use std::alloc::{Layout, alloc};
use std::ptr;

fn main() {
	static NULL: *mut u8 = ptr::null_mut();

	unsafe {
		let new_alloc = alloc(Layout::from_size_align_unchecked(12, 4));
		if new_alloc == NULL {
			println!("allocation failed");
			return;
		}
		new_alloc.copy_from_nonoverlapping("Hello ".as_ptr(), 6);

		let mut s = String::from_raw_parts(new_alloc, 6, 12);
		s.push_str("world!");

		println!("{}", &s);
		let _v: Vec<u32> = Vec::from_raw_parts(s.leak().as_mut_ptr().cast(), 3, 3);
	}
}
Answer
error[E0277]: `*mut u8` cannot be shared between threads safely
 --> src\main.rs:5:15
  |
5 |     static NULL: *mut u8 = ptr::null_mut();
  |                  ^^^^^^^ `*mut u8` cannot be shared between threads safely
  |
  = help: the trait `Sync` is not implemented for `*mut u8`
  = note: shared static variables must have a type that implements `Sync`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `rusttest` (bin "rusttest") due to 1 previous error

The rest of the code is correct.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions