Fix Arena realloc bug

This commit is contained in:
2025-08-28 13:27:53 -04:00
parent a32356e298
commit a73a463936

View File

@@ -77,32 +77,29 @@ void *ArenaAllocator::realloc_raw(void *ptr, uint32_t old_size,
assert(current_block_ &&
"realloc called with non-null ptr but no current block exists");
// Assert that offset is large enough (should always be true for
// valid callers)
assert(current_block_->offset >= old_size &&
"offset must be >= old_size for valid last allocation");
if (current_block_->offset >= old_size) {
// Check if this was the last allocation by comparing with expected location
char *expected_last_alloc_start =
current_block_->data() + current_block_->offset - old_size;
// Check if this was the last allocation by comparing with expected location
char *expected_last_alloc_start =
current_block_->data() + current_block_->offset - old_size;
if (ptr == expected_last_alloc_start) {
// This is indeed the last allocation
if (new_size > old_size) {
// Growing - check if we have space
size_t additional_space_needed = new_size - old_size;
if (ptr == expected_last_alloc_start) {
// This is indeed the last allocation
if (new_size > old_size) {
// Growing - check if we have space
size_t additional_space_needed = new_size - old_size;
if (current_block_->offset + additional_space_needed <=
current_block_->size) {
// We can extend in place
current_block_->offset += additional_space_needed;
return ptr;
if (current_block_->offset + additional_space_needed <=
current_block_->size) {
// We can extend in place
current_block_->offset += additional_space_needed;
return ptr;
}
} else {
// Shrinking - just update the offset
size_t space_to_free = old_size - new_size;
current_block_->offset -= space_to_free;
return new_size == 0 ? nullptr : ptr;
}
} else {
// Shrinking - just update the offset
size_t space_to_free = old_size - new_size;
current_block_->offset -= space_to_free;
return new_size == 0 ? nullptr : ptr;
}
}