Is it better to switch to C for my simple memory allocator?

I am writing a simple memory allocator in Rust, and am having difficulties with lifetimes and aliasing. Specifically, at various points, I need to:

  • reclaim the storage held by internal data structures, casting it into raw memory that can be later overwritten at will.
  • have data with lifetimes that are unknown and unknowable (from the allocator's perspective) – the host application controls them.
  • use raw pointers everywhere, since &mut pointers are not allowed to alias.
  • use unsafe code everywhere, due to the above.

Is it time to give up on Rust? Or is there a way to make writing such code easier?

Isn't this a usecase? For unsafe Rust? IMHO unsafe rust is still more programmer friendly than plain ole c.

Memory-safety, which you can't use, is not the only feature of Rust.

Do you find use for efficient iterators, generics, closures, smarter enums?

It sounds like you need to use mem::forget when you pass the pointer into the C code, and use Box::from_raw when it comes back from the C code.

In that way your rust code would just be operating on normal rust objects and you only have the trickery around the C interface.

1 Like

Or possibly Box::into_raw when you need to pass the pointer to the C code would be fine...not sure exactly what you are trying to do.

When I am coalescing free chunks, I need to make memory that was occupied by a struct part of a larger chunk, which means that it could later be overwritten by anything – including something that is not a valid value for the primitive types that the struct contained. As I understand it this is undefined behavior.

The only language where this might be UB is C/C++. It is definitely not UB in Rust.

I don't think there is any major advantage for writing an allocator in C vs. Rust, but if you are already in a Rust codebase, use it!