How to write a Rust program's heap memory contents into a file?

I'm looking for something similar to the runtime/debug/WriteHeapDump in Go.

Is there any method to do such a thing without using external debug tools?

Nothing platform-independent, at least. Rust doesn't even guarantee that there is a heap - it delegates that to an allocator, whose default implementation varies by platform and which may not be present at all (eg. in a no_std program designed for an embedded device).

You can trigger a core dump using platform-dependent features, which will usually get you a complete image of your program's memory at that point in time, although in practice the details vary a lot and are often heavily configurable. On Unix-like OSes, that's usually done by sending any of a few signals to your own process, which can be done through the nix crate pretty easily. Note that most signals that can cause a core dump also terminate the process, however.

Some debuggers can also force a core dump from the process they're attached to, usually without forcing it to exit. There are also crates for causing a core dump on panic, if you'd prefer to capture one automatically if and when your program encounters a problem outside of your normal error handling.

Depending on what you want a heap dump for, you could also write your own allocator as a wrapper around the default allocator, to log allocations and deallocations, or even use a slab allocator or a full-blown garbage collector for the relevant allocations and use its debugging features to track down whatever it is you need.


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.