4
votes

I was reading an article which says that Rust has a compiler option to disable heap allocation:

Rust has a number of standard library features that rely on the heap, like boxes. However, Rust has compiler directives to completely disable any heap-using language features, and statically verify that none of these features are being used. It is entirely practical to write a Rust program with no heap usage.

The ability to check for any mistaken heap allocations at compile-time would be very valuable to me. Exactly how do you do this in Rust? I don't see any relevant flags in the rustc man page.

1

1 Answers

6
votes

There is no such compiler flag, although I don't think that's what the article meant:

Rust has compiler directives

I'd parse "directive" as an attribute, something like #[foo]. There's still no attribute that I'm aware of that accomplishes this goal.

Note that your article predates Rust 1.0:

Rust, version 0.11


The closest you can get is to avoid using the standard library and only using the core library. This eschews the use of liballoc, the primary mechanism for allocation. Doing this prevents types like Box or String from even existing, which is a pretty strong static guarantee.

#![no_std]

pub fn example() {
    Box::new(42);
}
error[E0433]: failed to resolve. Use of undeclared type or module `Box`
 --> src/lib.rs:4:5
  |
4 |     Box::new(42);
  |     ^^^ Use of undeclared type or module `Box`

However, nothing can stop you from rewriting the same code that is in liballoc and allocating memory yourself. You could also link against existing libraries that allocate memory. There's no magic compiler pass that detects heap allocation.

See also: