轉載:http://hi.baidu.com/freelonely/blog/item/340341077c4d287302088189.html
預對齊內存的分配
在大多數情況下,編譯器和C庫透明地幫你處理對齊問題。POSIX 標明瞭通過malloc( ), calloc( ), 和 realloc( ) 返回的地址對於任何的C類型來說都是對齊的。
在Linux中,這些函數返回的地址在32位系統是以8字節爲邊界對齊,在64位系統是以16字節爲邊界對齊的。
有時候,對於更大的邊界,例如頁面,程序員需要動態的對齊。雖然動機是多種多樣的,但最常見的是直接塊I/O緩存的對齊或者其它的軟件對硬件的交互,因此,POSIX 1003.1d提供一個叫做posix_memalign( )的函數:
/* one or the other -- either suffices */
#define _XOPEN_SOURCE 600
#define _GNU_SOURCE
#include <stdlib.h>
int posix_memalign (void **memptr,
size_t alignment,
size_t size);
* See http://perens.com/FreeSoftware/ElectricFence/ and http://valgrind.org, respectively.
調用posix_memalign( )成功時會返回size字節的動態內存,並且這塊內存的地址是alignment的倍數。參數alignment必須是2的冪,還是void指針的大小的倍數。返回的內存塊的地址放在了memptr裏面,函數返回值是0.
調用失敗時,沒有內存會被分配,memptr的值沒有被定義,返回如下錯誤碼之一:
EINVAL
參數不是2的冪,或者不是void指針的倍數。
ENOMEM
沒有足夠的內存去滿足函數的請求。
要注意的是,對於這個函數,errno不會被設置,只能通過返回值得到。
由posix_memalign( )獲得的內存通過free( )釋放。用法很簡單:
char *buf;
int ret;
/* allocate 1 KB along a 256-byte boundary */
ret = posix_memalign (&buf, 256, 1024);
if (ret) {
fprintf (stderr, "posix_memalign: %s\n",
strerror (ret));
return -1;
}
/* use 'buf'... */
free (buf);
Refer: 1.函數API說明 https://pubs.opengroup.org/onlinepubs/007904975/functions/posix_memalign.html