简体   繁体   中英

how portable are unaligned read / write?

let's say I have a struct of type A that is POD, and a void pointer p .

Can I safely cast p to a pointer to A , then read/write to the A structure pointed by p ? Is it guaranteed to work everytime, even if the alignment of A is 8 and p points to an odd memory adress? (worst case)

I am not concerned about performance issues, I just want to know if it's supposed to work according to the standard and / or if it's portable enough on mainstream platforms.

edit : I'm also interested to know if there's any difference depending on x86 / 64 bits architecture

Thanks!

Yes, you can cast a pointer to class A to a class B.

Essentially, you are telling the compiler to use stencil class B when referring to the memory location of the class A variable.

Generally, this is not safe because the values at the locations will have different meanings and positions.

Usually, this type of casting is used for interpreting a buffer of uint8_t as a structured object. Another usage is when there is a union .

So the term safe depends on the context that the operation is used in.

Edit 1: Alignment
Most modern processors can handle alignment issues. The processor may require more operations to fetch the data, which will slow down the performance.

For example with a 16-bit processor, a 16-bit value aligned on an odd address will require two fetches (since it only fetches at event addresses):

+----------+----------------------------+  
|  address | value                      |  
+----------+----------------------------+  
|  16      |  N/A                       |  
+----------+----------------------------+  
|  17      | 1st 8 bits of 16-bit value |  
+----------+----------------------------+  
|  18      | 2nd 8 bits of 16-bit value |  
+----------+----------------------------+  
|  19      |  N/A                       |  
+----------+----------------------------+  

Since the processor only fetches values at even addresses, fetching the value will require 2 fetches. The first fetch at address 16 obtains the first 8 bits of the 16-bit variable. The second fetch obtains the second 8 bits of the variable.

The processor also has to perform some operations to get the bits in the preferred order in one "word". These operations will also negatively affect the performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM