diff --git a/ya_block.c b/ya_block.c index a518aef..686a2bd 100644 --- a/ya_block.c +++ b/ya_block.c @@ -53,6 +53,10 @@ static inline intptr_t round_to(intptr_t n, intptr_t m) { return round_div(n,m) * m; } +static inline intptr_t inner_bytes(intptr_t *block) { + return (block_size(block) - 4) * WORD_SIZE; +} + /*----------------------*/ /* Function definitions */ /*----------------------*/ @@ -201,9 +205,18 @@ intptr_t *heap_init() { return heap_start; } -/* Extends the heap by at least n_bytes bytes by calling sbrk. +/* Extends the heap enough for the last block to be at least n_bytes bytes + * large by calling sbrk. * Returns a pointer to the last (free) block or NULL in case of failure. */ intptr_t *heap_extend(size_t n_bytes) { + intptr_t *last = fl_get_end(); + if (last) { + intptr_t last_bytes = inner_bytes(last); + if (last_bytes >= n_bytes) { + return last; + } + n_bytes -= last_bytes; + } // request an integer number of blocks intptr_t size = block_fit(round_to(n_bytes, CHUNK_SIZE)); void *ptr = sbrk(WORD_SIZE * size); diff --git a/ya_block.h b/ya_block.h index e5f3d6b..bcf9981 100644 --- a/ya_block.h +++ b/ya_block.h @@ -63,7 +63,8 @@ static inline intptr_t block_size(intptr_t *block) { * Returns the pointer to the start of the heap or NULL in case of failure. */ intptr_t *heap_init(); -/* Extends the heap by at least n_bytes bytes by calling sbrk. +/* Extends the heap enough for the last block to be at least n_bytes bytes + * large by calling sbrk. * Returns a pointer to the last (free) block or NULL in case of failure. */ intptr_t *heap_extend(size_t n_bytes); diff --git a/ya_freelist.c b/ya_freelist.c index 784265b..e48423e 100644 --- a/ya_freelist.c +++ b/ya_freelist.c @@ -147,3 +147,13 @@ void fl_join(intptr_t *block) { fl_join_next(block); fl_join_prev(block); } + +/* Returns a pointer to the first free block. */ +intptr_t *fl_get_start() { + return fl_start; +} + +/* Returns a pointer to the last free block. */ +intptr_t *fl_get_end() { + return fl_end; +} diff --git a/ya_freelist.h b/ya_freelist.h index dd7563d..6824d7e 100644 --- a/ya_freelist.h +++ b/ya_freelist.h @@ -71,4 +71,10 @@ void fl_join_next(intptr_t *block); void fl_join(intptr_t *block); +/* Returns a pointer to the first free block. */ +intptr_t *fl_get_start(); + +/* Returns a pointer to the last free block. */ +intptr_t *fl_get_end(); + #endif