【问题标题】:Memory alignment requirement for data transfer with Direct I/O使用 Direct I/O 进行数据传输的内存对齐要求
【发布时间】: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;

【问题讨论】:

    标签: c linux malloc glibc


    【解决方案1】:

    这里的作者想要一个有n字节对齐但不是2n字节对齐的缓冲区,大概是为了演示由于对齐不足或类似的原因而失败(我没有书)。

    他通过请求一个 2n 字节对齐的缓冲区(显然也有 n 字节对齐)然后添加 n 来实现这一点。这打破了 2n 字节对齐,但保持了 n 字节对齐。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-08
      • 2020-02-18
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多