Recognizing allocations


#1

I’ve seen multiple mentions that heap allocations in Rust are explicit and should remain so. However, Rust doesn’t have separate syntax for memory allocation.

Are there some naming conventions which indicate heap allocation?


#2

I suspect the reason why folks say “heap allocations in Rust are explicit” is because the language itself won’t insert any heap allocations for you behind your back. In particular, it should be feasible to use Rust in environments with no dynamic heap allocation. In order for that to be able to work, the language really can’t go and add heap allocations for you.

However, library code can certainly allocate without you knowing. A library you use might use a String or Vec or a HashMap internally, all of which will certainly allocate.

Here are some heuristics I use in daily life:

  • Is the type a standard data structure from std like String, Vec, BTreeMap or HashSet? If yes, then there’s an allocation.
  • Does my type contain a Box or an Rc or an Arc? If yes, then there’s an allocation.
  • Is my type Copy? If yes, then there’s probably no allocation going on. If no, then maybe there’s allocation. (Not always true, but again, we’re talking about heuristics here.)

Unless you have a specific requirement with respect to allocation, I think the more important question here is not “does something allocate,” but rather, “is allocation responsible for my program running too slowly?” The latter can typically be answered through profiling tools.


#3

I suppose it also means you can use an alternative standard library which uses a different kind of allocation interface.

The other aspect is that allocation can fail. I’m not sure to what degree catch_unwind is supported today. But if you want to catch memory allocation errors reliably, you need to make sure that Drop handlers themselves do not allocate.


#4

AFAIK, Rust’s standard library currently aborts if allocation fails. You can’t recover from it. I don’t know if anyone is working on fixing this to make it so allocation panics instead of aborts, which would afford some opportunity for recovery.


#5

I think there is work being done on it. In general, it is a difficult problem, since it requires that destructors never allocate.