编写跨平台代码之memory alignment

    编写网络包(存储在堆上)转换程序时,在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架构, 不支持内存随机存取,须要作字节序对齐操做。express

   当将内存数据类型进行强制转换后,随机读取的field1 地址颇有可能不在一次可读取的地址上(如,地址为0X0001-0X0005), 此时便会抛出bus_adraln错误,致使宕机。网络

如:架构

struct SHead{
uint32_t field1;
uint32_t field2;
};

SHead *head = (SHead*)buf;
printf("%d\n", head->field1);

  一种解决方案是多一次内存拷贝,如:app

struct SHead{
uint32_t field1;
uint32_t field2;
};

SHead head;
memcpy(&head, buf, sizeof(SHead));
printf("%d\n", head.field1);

  

msdn上对内存字节对齐的介绍:ui

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.code

Misaligned memory accesses can incur enormous performance losses on targets that do not support them in hardware.orm

 

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.blog

An address is said to be aligned to X if its alignment is Xn+0.内存

 

 

对内存对齐不是很熟悉的同窗请参考: get

http://msdn.microsoft.com/en-us/library/ms253949(VS.80).aspx

相关文章
相关标签/搜索