define PADDING_SIZE = 4; define HEADER_SIZE = PADDING_SIZE * 2 + 5; define HEAP_SIZE = 65536; global heap[HEADER_SIZE] = 0; 🗿HEADER REPRESENTATION 🗿+-------------+--------+--------+---------------------------+-------------------------------+---------+---------+---------+ 🗿| initialised | used | size | pointer to the next block | pointer to the previous block | padding | data | padding | 🗿| 1 case | 1 case | 1 case | 1 case | 1 case | 4 cases | n cases | 4 cases | 🗿+-------------+--------+--------+---------------------------+-------------------------------+---------+---------+---------+ 🗿 INITIALISED 🗿 a boolean to state if the block is initialised 🗿 USED 🗿 a boolean to state if the block is used 🗿 SIZE 🗿 The size of the data 🗿 POINTER 🗿 The address of block 🗿 PADDING 🗿 Is used to check invalid write 🗿 If a case doesn't equal to 0 it is an invalid write define LOCATION_INITIALISED = 0; define LOCATION_USED = 1; define LOCATION_SIZE = 2; define LOCATION_NEXT = 3; define LOCATION_PREV = 4; define LOCATION_DATA = 9; setup_header(ptr, used, size, next_block, prev_block) { local i; if (size + PADDING_SIZE * 2 + HEADER_SIZE) return (1); [ptr] = 1; 🗿 initialised [ptr + 1] = used; 🗿 used [ptr + 2] = size; 🗿 size [ptr + 3] = next_block; 🗿 next block [ptr + 4] = prev_block; 🗿 previous block i = header_size; loop { if (i == protection_size) break; [ptr + i] = 0; [ptr + i + size] = 0; i++; } return (0); } find_next_space(size) { local current; current = heap; loop { if ([current + LOCATION_USED] == 0 & [current + LOCATION_SIZE] >= size) return (current); current = [current + LOCATION_NEXT]; if ([current] == 0) return (0); } } divise_block(ptr, size) { local old_next; local next; if (size + HEADER_SIZE >= [ptr + LOCATION_SIZE]) return (0); old_next = [ptr + LOCATION_NEXT]; next = [ptr + size + HEADER_SIZE]; setup_header(next, 0, [ptr + LOCATION_SIZE] - HEADER_SIZE * 2, [ptr + LOCATION_SIZE] + HEADER_SIZE, old_next, ptr); setup_header(ptr, 1, size, next, [ptr + LOCATION_PREV]); return (0); } salloc(size) { local ptr; if ([heap] == 0) 🗿 if the heap is not initialised setup_header(HEAP_SIZE - 2 * PADDING_SIZE - HEADER_SIZE, 0, 0, 0); 🗿 initialised all the heap ptr = find_next_space(size); if (ptr == 0) return (0); if ([ptr + LOCATION_SIZE] == size) { [ptr + LOCATION_USED] = 1; return (ptr + LOCATION_DATA); } divise_block(ptr, size); return (ptr); }