Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust manual memory management

When I began learning C, I implemented common data structures such as lists, maps and trees. I used malloc, calloc, realloc and free to manage the memory manually when requested. I did the same thing with C++, using new and delete.

Now comes Rust. It seems like Rust doesn't offer any functions or operators which correspond to the ones of C or C++, at least in the stable release.

Are the Heap structure and the ptr module (marked with experimental) the ones to look at for this kind of thing?

I know that these data structures are already in the language. It's for the sake of learning.

like image 607
LppEdd Avatar asked Jan 28 '18 10:01

LppEdd


People also ask

Does Rust have manual memory management?

One of the key features of Rust that sets it apart from other new languages is that its memory management is manual—the programmer has explicit control over where and how memory is allocated and deallocated. In this regard, Rust is much more like C++ than like Java, Python, or Go, to name a few.

Does Rust have automatic memory management?

Rust does not have automatic memory management; it has manual memory management which the compiler checks for correctness. The difference might sound theoretical, however it is important because it means that the memory operations map directly to the source code, there is no magic going on behind the scenes.

Does Rust have dynamic memory allocation?

The items of a program are those functions, modules, and types that have their value calculated at compile-time and stored uniquely in the memory image of the rust process. Items are neither dynamically allocated nor freed.

Does Rust have malloc?

> Rust uses malloc provided by the system. It doesn't lock you into the system allocator. You can LD_PRELOAD your own, and in the past Rust has even shipped with and used jemalloc[1] (though I believe it's not using it at the moment).


1 Answers

Although it's really not recommended to do this ever, you can use malloc and free like you are used to from C. It's not very useful, but here's how it looks:

extern crate libc; // 0.2.65

use std::mem;

fn main() {
    unsafe {
        let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>() as libc::size_t) as *mut i32;
        if my_num.is_null() {
            panic!("failed to allocate memory");
        }
        libc::free(my_num as *mut libc::c_void);
    }
}

A better approach is to use Rust's standard library:

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

fn main() {
    unsafe {
        let layout = Layout::new::<u16>();
        let ptr = alloc(layout);

        *(ptr as *mut u16) = 42;
        assert_eq!(*(ptr as *mut u16), 42);

        dealloc(ptr, layout);
    }
}
like image 145
tomer zeitune Avatar answered Oct 10 '22 23:10

tomer zeitune