Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 240 – Lecture 21 Alloc Implementation.

Similar presentations


Presentation on theme: "CS 240 – Lecture 21 Alloc Implementation."— Presentation transcript:

1 CS 240 – Lecture 21 Alloc Implementation

2 Discussions on hw9 Memory Allocation Exercise 3 functions:
void initalloc(void); char * alloc(int n); void freef(char *p); You are asked to write the freef() function The alloctest.c program is provided to test the functions

3 initalloc function Initializes a large free buffer F allocbuf
struct blockl{ unsigned int tag:8; unsigned int size :24; struct blockl *nextp; struct blockl *prevp;}; Blockrp = allocbuf + ALLOCSIZE -TAGSIZE Cursorp = freep = allocbuf F allocbuf TAGSIZE ALLOCSIZE Struct blockr{ unsigned int tag:8; unsigned int size:24;}; TAGSIZE = sizeof(blockr) MINFREESIZE= sizeof(blockl) + sizeof(blockr) USEDTAG = 0xaa FREETAG = 0x55

4 Function alloc(n) U U Allocate a buffer of
allocsize = n (in multiple of 4 ) + 2*TAGSIZE bytes from the free buffer pool The tags for both ends of the allocated buffer are of type struct blockr. They are not kept using a linked list (no need for the char * elements) Function returns a pointer = holdp + TAGSIZE holdp pointer returned by alloc U U n bytes in multiple of 4 TAGSIZE TAGSIZE

5 Allocation Algorithm I) cursorp->size < allocsize=4*((n-1)/4 +1) +2*TAGSIZE return null if all free blocks are not big enough II) cursorp->size <allocsize + MINFREESIZE return pointer =holdp + TAGSIZE III) cursor->size > allocsize + MINFREESIZE p=cursorp=holdp blockrp = p +holdp->size -TAGSIZE U allocsize U blockrp =p + allocsize-TAGSIZE cursorp allocsize F U new free size holdp = p blockrp = p-TAGSIZE

6 Enchaining Free Buffers
Allocated buffers are not chained An example of chaining 4 free buffers Most recent freep cursorp Least recent BUF 4 BUF 3 BUF 2 BUF 1 nextp =3 prevp =1 nextp =2 nextp =1 nextp =4 prevp =4 prevp =3 prevp =2

7 Unchaining free buffers
Most recent Least recent BUF 4 BUF 3 BUF 2 BUF 1 nextp =3 prevp =1 nextp =2 nextp =1 nextp =4 prevp =4 prevp =3 prevp =2 freep cursorp BUF 4 BUF 2 BUF 1 nextp =2 prevp =1 nextp =1 nextp =4 prevp =4 prevp =2

8 Multiple cases of freef
Left block is not free Case 1: Left block is free F F U U F F Case 3: Both left and right blocks are free

9 Pseudocode for freef(char *p)
p is the same pointer obtained from alloc() Change tag to FREETAG on blockl Change tag to FREETAG on blockr No need to update size on blockl and blockr because alloc() sets the sizes correctly Check if block on left is also free? case 1: yes, coalesce free block on left and p case 2: no, enchain buffer Check if block on right is also free? case 3: yes, unchain the block on right and coalesce p with block on right. return


Download ppt "CS 240 – Lecture 21 Alloc Implementation."

Similar presentations


Ads by Google