commit bdbe9797060b943d71bb021219aba3ec5933f293
parent fc7dca9becff7a32f710ad63737c1be3dfaed3a3
Author: Chris Bracken <chris@bracken.jp>
Date: Fri, 21 Oct 2022 23:09:19 -0700
Only mark the block as free if it's still around
In the case where the block to be freed is the last one, we're
decrementing the break below the whole allocation including the header.
In that case, it's not only pointless to mark the block as free, it's
almost certainly Wrong (TM) to do so.
Diffstat:
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/src/main.cc b/src/main.cc
@@ -89,10 +89,9 @@ void free(void *block) {
// Get block header.
struct header_t *header = static_cast<struct header_t*>(block) - 1;
- // Check if we're the last allocated block before brk.
void *program_break = sbrk(0);
-
if (static_cast<char*>(block) + header->size == program_break) {
+ // If we're the last allocated block before brk, decrement it.
if (head == tail) {
head = tail = nullptr;
} else {
@@ -107,9 +106,11 @@ void free(void *block) {
sbrk(-static_cast<int>(total_size));
pthread_mutex_unlock(&global_malloc_lock);
return;
+ } else {
+ // Otherwise, mark the block as free.
+ header->is_free = 1;
}
- header->is_free = 1;
pthread_mutex_unlock(&global_malloc_lock);
}