我正在阅读Michael Kerrisk的“Linux编程接口”。 我正在通过memalign()用于alignment要求的示例 。
代码和评论对我来说没有意义。 任何人都可以解释为什么我们需要2 *alignment?
/* 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;
作者在这里想要一个有n字节对齐但不是2n字节对齐的缓冲区,可能是因为对齐不够或者类似的东西(我没有这本书)来演示失败。
他通过要求2n字节对齐的缓冲区(显然也有n字节对齐)然后添加n来实现这一点。 这打破了2n字节的对齐,但保持了n字节对齐。