34

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.

1
  • Manual allocation is deep into unsafe Rust territorry, it's covered pretty well in the Rustonomicon
    – Misty
    Jul 8, 2021 at 9:13

3 Answers 3

30

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);
    }
}
2
  • Not necessarily should you "only use it if you want to create your own smart pointer". Jan 28, 2021 at 21:34
  • It's omcprrect to say you should never do this, amlloc is slow and real time systems often allocate their own memory by first a single call to malloc and then managing their own memory.
    – Makogan
    Jul 31, 2022 at 9:26
25

It's very unusual to directly access the memory allocator in Rust. You generally want to use the smart pointer constructors (Box::new, Rc::new, Arc::new) for single objects and just use Vec or Box<[T]> if you want a heap-based array.

If you really want to allocate memory and get a raw pointer to it, you can look at the implementation of Rc. (Not Box. Box is magical.) To get its backing memory, it actually creates a Box and then uses its into_raw_non_null function to get the raw pointer out. For destroying, it uses the allocator API, but could alternatively use Box::from_raw and then drop that.

7
  • 2
    Why would you want to?
    – doron
    Jan 28, 2018 at 11:08
  • Then first you make absolutely sure it can't be implemented in terms of the existing ones. And in the unlikely case that that's really so, you can either use the allocator API, or use malloc from the libc crate. Jan 28, 2018 at 11:10
  • 1
    Note that the Rust standard library for stable Rust can use unstable features internally, and as such is privileged over normal code. Jan 28, 2018 at 11:11
  • 1
    Doron, just because I like to do so. I certainly don't aim to use my own in production.
    – LppEdd
    Jan 28, 2018 at 11:13
  • 2
    @LppEdd manishearth.github.io/blog/2017/01/10/… Jan 28, 2018 at 22:05
17

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

No, as a beginner you absolutely shouldn't start there. When you started learning C, malloc was all there was, and it's still a hugely error-prone part of the language - but you can't write any non-trivial program without it. It's very important for C programmers to learn about malloc and how to avoid all the pitfalls (memory leaks, use-after-free, and so on).

In modern C++, people are taught to use smart pointers to manage memory, instead of using delete by hand, but you still need to call new to allocate the memory for your smart pointer to manage. It's a lot better, but there's still some risk there. And still, as a C++ programmer, you need to learn how new and delete work, in order to use the smart pointers correctly.

Rust aims to be much safer than C or C++. Its smart pointers encapsulate all the details of how memory is handled at low-level. You only need to know how to allocate and deallocate raw memory if you're implementing a smart pointer yourself. Because of the way ownership is managed, you actually need to know a lot more details of the language to be able to write correct code. It can't be lesson one or two like it is in C or C++: it's a very advanced topic, and one many Rust programmers never need to learn about.

If you want to learn about how to allocate memory on the heap, the Box class is the place to start with that. In the Rust book, the chapter about smart pointers is the chapter about memory allocation.

9
  • 1
    I perfectly understand that smart pointers are the way to go. But they're only containers which internally must use the aforementioned keywords. As I commented on Sébastien answer, what if I'm curious on implementing my own memory container?
    – LppEdd
    Jan 28, 2018 at 11:08
  • 13
    "In modern C++, […] but you still need to call new to allocate the memory for your smart pointer to manage." -> No. In modern C++ people use std::make_unique and std::make_shared.
    – mcarton
    Jan 28, 2018 at 12:04
  • 3
    "if I read a book about Cpp, it's the first thing I learn about" How old is that book?
    – mcarton
    Jan 28, 2018 at 12:05
  • 7
    If you write new in C++11 (and beyond), you are asking for trouble. std::vector and std::make_unique should cover 99% of your use cases, std::shared_ptr 99% of the remaining cases. The odd use of new should be strictly reserved to implementing higher-level abstractions in foundational libraries. Jan 28, 2018 at 12:44
  • 2
    Btw, Stroustrup begin talking about pointers and memory management at page 171 of its own book.
    – LppEdd
    Jan 28, 2018 at 13:11

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.