使用Direct I / O进行数据传输的内存对齐要求

时间:2014-08-10 23:08:21

标签: c linux malloc glibc

我正在阅读Michael Kerrisk的Linux编程接口。我正在浏览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;

1 个答案:

答案 0 :(得分:2)

这里的作者想要一个具有n字节对齐但不是2n字节对齐的缓冲区,大概是为了证明由于对齐不充分或类似的事情导致的失败(我没有这本书)。

他通过要求具有2n字节对齐的缓冲区(显然也具有n字节对齐)然后添加n来实现此目的。这会打破2n字节的对齐,但保持n字节对齐。