编写网络包(存储在堆上)转换程序时,在hp-ux机器上运行时会遇到 si_code: 1 - BUS_ADRALN - Invalid address alignment. Please refer to the following link that helps in handling unaligned data 错误,经排查,是由于hp-ux 的cpu基于IA-64架构, 不支持内存随机存取,需要做字节序对齐操作。
当将内存数据类型进行强制转换后,随机读取的field1 地址很有可能不在一次可读取的地址上(如,地址为0X0001-0X0005), 此时便会抛出bus_adraln错误,导致宕机。
如:
struct SHead{ uint32_t field1; uint32_t field2; }; SHead *head = (SHead*)buf; printf("%d ", head->field1);
一种解决方案是多一次内存拷贝,如:
struct SHead{ uint32_t field1; uint32_t field2; }; SHead head; memcpy(&head, buf, sizeof(SHead)); printf("%d ", head.field1);
msdn上对内存字节对齐的介绍:
Many CPUs, such as those based on Alpha, IA-64, MIPS, and SuperH architectures, refuse to read misaligned data. When a program requests that one of these CPUs access data that is not aligned, the CPU enters an exception state and notifies the software that it cannot continue. On ARM, MIPS, and SH device platforms, for example, the operating system default is to give the application an exception notification when a misaligned access is requested.
Misaligned memory accesses can incur enormous performance losses on targets that do not support them in hardware.
Alignment is a property of a memory address, expressed as the numeric address modulo a power of 2. For example, the address 0x0001103F modulo 4 is 3; that address is said to be aligned to 4n+3, where 4 indicates the chosen power of 2. The alignment of an address depends on the chosen power of two. The same address modulo 8 is 7.
An address is said to be aligned to X if its alignment is Xn+0.
对内存对齐不是很熟悉的同学请参考:
http://msdn.microsoft.com/en-us/library/ms253949(VS.80).aspx