編寫跨平臺代碼之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

相關文章
相關標籤/搜索