Does deref a raw pointer requires that pointer to be properly aligned?

I'm writing a binary parser. I receive the data through a raw pointer (*const u8) point to a buffer.
Does deref a raw pointer of type *const T requires that pointer to be properly aligned with align_of::<T>()?

Take a look at the module description of std::ptr:

Valid raw pointers as defined above are not necessarily properly aligned (where "proper" alignment is defined by the pointee type, i.e., *const T must be aligned to mem::align_of::<T>() ). However, most functions require their arguments to be properly aligned, and will explicitly state this requirement in their documentation. Notable exceptions to this are read_unaligned and write_unaligned .

When a function requires proper alignment, it does so even if the access has size 0, i.e., even if memory is not actually touched. Consider using NonNull::dangling in such cases.


I recommend you avoid using unsafe to begin with, and only optimize things with it afterwards, when and where you find performance issues.

For instance, given your use case, it looks like you could definitely be using the ::zerocopy crate :slight_smile:

Thanks all. In the end, I used pointer::read_unaligned. I cannot use ::zerocopy crate because
the types and information extracted from raw buffer need processing.