Are uninitialized allocations from FFI also "uninitialized" in Rust?

What the compiler knows is irrelevant for the question of soundness. There, the only thing that matters is what your code does. If your code does allowed stuff, then it's sound, and if it triggers UB, then it's unsound. End of story.

Now, the question of "does it get miscompiled?" is, of course, a different story. If you call into unknown C FFI code and then use the memory as-if it was initialized, then we get two cases:

  1. The FFI code initialized it. All is good, and the compiler does what you want.
  2. The FFI code didn't initialize it. Your code triggers UB, and the compiler is allowed to do anything it wants. Since the compiler doesn't know about this, it chooses to compile it into what you wanted.

So you might argue that you get what you wanted in either case. However, the second case is still unsound! After all, UB allows everything, and doing what you wanted is included in everything.


All that said, the compiler does know what malloc does, so it's fully aware that your memory is uninitialized. Even if you wrapped in a custom C FFI function, the compiler could learn of this during link-time-optimization. Only dynamic libraries are truly be unknown to the compiler.

However, you can argue that is sound in an entirely different way. See this thread for more on that.

4 Likes