【发布时间】:2014-08-10 23:08:21
【问题描述】:
我目前正在阅读 Michael Kerrisk 的 The Linux Programming Interface。我正在查看example,其中 memalign() 用于对齐要求。
代码和评论对我来说没有意义。谁能解释为什么我们需要 2 * 对齐?
/* memalign() allocates a block of memory aligned on an address that
is a multiple of its first argument. By specifying this argument as
2 * 'alignment' and then adding 'alignment' to the returned pointer,
we ensure that 'buf' is aligned on a non-power-of-two multiple of
'alignment'. We do this to ensure that if, for example, we ask
for a 256-byte aligned buffer, we don't accidentally get
a buffer that is also aligned on a 512-byte boundary. */
buf = memalign(alignment * 2, length + alignment);
if (buf == NULL)
errExit("memalign");
buf += alignment;
【问题讨论】: