explanation to aligned malloc implementation

后端 未结 4 2007
旧巷少年郎
旧巷少年郎 2021-02-04 07:33

This is not homework, this is purely for my own personal education.

I couldn\'t figure out how to implement an aligned malloc so looked online and found this website. Fo

4条回答
  •  孤独总比滥情好
    2021-02-04 08:10

    Suppose we need SZ bytes of aligned memory, let:

    A is the alignment.
    W is the CPU word size.
    P is the memory returned by malloc.
    SZ is the requested number of bytes to be allocated.
    

    we will return (P + Y) in which (P + Y) mod A = 0

    So, we should save the original pointer P to be able to free the memory later. In this case, we should allocate (SZ + W) bytes, but to let memory aligned, we will substruct Z bytes in which (P % A = Z) => (Z ∈ [0, A-1])

    So the total memory to be allocated is:  SZ + W + MAX(Z) = SZ + W + A - 1
    

    The pointer to be returned is P + Y = P + W + MAX(Z) - (P + W + MAX(Z)) mod A

    WE HAVE: X - X mod A = INT(X / A) * A = X & ~(A - 1)

    SO we can replace P + W + MAX(Z) - (P + W + MAX(Z)) mod A by (P + W + MAX(Z)) & ~(A - 1)

    The memory to be returned is: (P + W + MAX(Z)) & ~(A - 1) = (P + W + A - 1) & ~(A - 1)
    

提交回复
热议问题