3

I've came accross this post that explains that in C, structs can't be zero-sized and must have at least one named field to not be UB.

However, in Rust, we can have such structs. And we can also mark structs as #[repr(C)] that will, from the docs, "do what C does".

So naturally, I went out to the playground to try this:

#[repr(C)]
struct ZeroSized;

fn main() {
    println!("Size: {}", std::mem::size_of::<ZeroSized>());
}

And this code does print out 0.

I was wondering does Rust allows #[repr(C)] zero sized structs if they are forbidden, and even UB, in C?

Will the final size of such a struct actually be 0? What would happen if I copy this struct around in memory? Can I even have a pointer to it?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • The question is interesting, but I cannot imagine any real situation where we would have to share a ZST between Rust and C. Could you suggest an example? – prog-fh Aug 27 '23 at 08:42

1 Answers1

5

I suggest you read further in the documentation on repr

ZSTs are still zero-sized, even though this is not a standard behavior in C, and is explicitly contrary to the behavior of an empty type in C++, which says they should still consume a byte of space.

To answer your questions:

I was wondering does Rust allows #[repr(C)] zero sized structs if they are forbidden, and even UB, in C? Will the final size of such a struct actually be 0?

Yes, and yes, see above.

What would happen if I copy this struct around in memory?

As with any ZST the compiler will most likely omit the copies

Can I even have a pointer to it?

As with any ZST yes.

jthulhu
  • 7,223
  • 2
  • 16
  • 33
cafce25
  • 15,907
  • 4
  • 25
  • 31
  • 1
    This goes for rust side of things, but trying to read a pointer to a rust ZST from C is likely to be an UB, as far as I understand? – Ivan C Aug 27 '23 at 08:02
  • @IvanC If it points to a ZST, yes. If it doesn't, and it's just that its type is of a pointer to ZST, then it's fine to read it (with its actual type). – Chayim Friedman Aug 27 '23 at 09:48