Is it safe to free data in C code that was malloc'd in Rust code?

Say I have a Rust function meant to be called from C code:

#[unsafe(no_mangle)]
extern "C" fn foo() -> *mut u8 {
  unsafe { libc::malloc(42) }
}

Can I free the return value of this function in C code with:

#include <stdlib.h>

int main(void) {
  uint8_t* x = foo();
  free(x);
  return 0;
}

Are there any dangerous assumptions being made here using free to free the return value of foo?

If they're compiled to a single binary, that should be fine. You're explicitly calling C's malloc, so the corresponding free is correct.

However, if this crosses shared libraries, like the rust code in a DLL and then a main binary, it may be trouble. I think Windows can potentially resolve each to a distinct C runtime, and then the malloc and free wouldn't match.

5 Likes