FFI Safety of Box<T>

When a type does not have an #[repr(...)] annotation, the memory layout of that type is 100% unspecified, and could be anything. Of course, if it happens to be what you expected in this particular instance, it will work, but then you are relying on internal compiler details.

The case of box is slightly interesting, because the standard library does make a promise in the documentation, so in this case it is ok. However you should be aware that the only reason they can make this promise is that Box has been implemented by the people who wrote the compiler, so they can make promises that rely on internal compiler details, and this is only because they also control the compiler, and control thus when and how these internal compiler details change.

As for “but this seems unnecessary as this works perfectly fine like this already”, that is a very dangerous argument when you are dealing with undefined behaviour. Let me quote myself

In this case it wasn't just luck, but the there are other cases where it will just be luck, and in those cases you could have made the same argument, and therefore it is a bad argument.

I don't know why they haven't just put #[repr(transparent)] on box.

6 Likes