Minimize bytes for wasting to align data between two headers (custom allocator)

Here is the memory layout in the user allocator: -

^ toward less address
....
Header                         [size=16     alignment=4      ] ....(1)
some waste space A             [size=A   (unknown)           ]
content                        [size="SIZE" alignment="ALIGN"] ....(2)
some waste space B             [size=B   (unknown)           ]
Header                         [size=16     alignment=4      ] ....(3)
....
v toward more address

The exact address is Headernot known in advance. However, I know that: -

every Header address % 4 == 0      from (1,3)
"content"%ALIGN          == 0      from (2)

Question

How to determine the minimum number of bytes for A+content+Bwhich all (1 & 2 & 3) are always aligned properly?

//return maximum size of A+content+B that make the allocation always safe
int wasteA_content_wasteB(int SIZE,int ALIGN){
    //???
}

My progress

If I approach the problem more mathematically: -

Header                  start at K1*4
some waste space A      
content                 start at K2*ALIGN
some waste space B       
Header                  start at K3*4
//K1 and K2 and K3 are unknown positive integer

I will get a system of inequalities: -

K1*4 + 16     <= K2*ALIGN
K2*ALIGN+SIZE <= K3*4

However, with my limited math background, I don’t know how to solve it.

The main difficulty is that I don’t know in advance K1, I have to use the result of function ( A+content+B) as a parameter to request a block of memory from a user heap allocator.

K1 . . :(

, ( ), , .

, : -

  • , , . return ceil((SIZE+max(4,ALIGN)-1)/ALIGN)*ALIGN
  • (, SIZE ALIGN) , .

... , . (?)

, (, ).
, .

+6
1

, ALIGN 2.

: ALIGN <= 4, ALIGN > 4.

ALIGN <= 4, content A == 0, Header is. B alignment == 4. , A + content + B == ceil(content/4)*4.

ALIGN > 4, , content ALIGN.

Header k*ALIGN - 12, , , A k*ALIGN + 4. ALIGN, A == ALIGN - 4, A + content == ALIGN + content - 4.

Header. B k'*ALIGN + content , , B == 4 - (content%4), , ALIGN 2 4. , A + content + B == ALIGN + content + (content%4) ALIGN + ceil(content/4)*4.

, content Header.

+2

All Articles