Rust no_std find why global memory allocator is required

I'm writing Rust code for a platform which doesn't have support for std or alloc, so I have to use only core. Recently, my code has started producing this compile error:

error: no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait

error: `#[alloc_error_handler]` function required, but not found

Is there a way I can get the rust compiler to tell me why a global memory allocator is required?

Presumably, somewhere in my code or my dependencies something is attempting to allocate and that's causing it to go wrong, but I can't figure out where this is happening. The only advice I saw online for this situation is to make a dummy custom allocator that simply errors on an attempted allocation and then look through the compiled binary for references to it. However, I did this and am unable to find any reference to my custom allocator in the binary executable that it produced, which is making me more confused as to what's going on (I've tried using objdump on the final binary and looking at all mentions of alloc or of the name of my custom allocator's type in it, to no avail).

From this, I assume that the allocation is coming from some snippet of code which isn't needed for the final executable but which is being compiled anyway. Does anyone have any tips for how to pin down what such code is causing this issue (or any other ideas of what might be causing it to need an allocator)?

The "no global memory allocator" error is triggered the moment anyone tries to link with alloc. So in theory, you should be able to grep for extern crate alloc through your entire dependency tree to find the offending crate.

The cargo vendor command will help here because it copies the source code for your dependencies into the vendor/ directory.

I ran into this recently as well. The advice I received was (if you can't get rid of the crate linking to alloc), is to simply add a stub allocator that allocates null and panics on deallocate. The panic on deallocate works because the GlobalAlloc specifies that a null returned from alloc indicates an allocation failure, so dealloc should never be called.

Thanks for this tip. Between your suggestion to use cargo vendor and then searching through the dependencies with ripgrep, I was able to figure out what dependency of mine was using it.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.