Fix bug in handmade_aligned_realloc
Reference issue
What does this implement/fix?
Addresses two bugs in handmade_aligned_realloc
:
-
memmove
the correct number of bytes fromnew_size
(used to besize
) tomin(old_size,new_size)
so as to not overrun the bounds of the allocated memory. Ifnew_size > old_size
, then the array was expanded, and we need to copy the entire original array (old_size
). Ifnew_size < old_size
, then the array was shrunk, and we need to copy the entire new array (new_size
). Thus, in general, we need the minimum of these two sizes. We explicitly avoid the case wherenew_size == old_size
, as the behavior is possibly undefined (at best, this would result in a no-op anyway). - If
std::realloc
returns a new address, the reallocation is performed by "allocating a new memory block of sizenew_size
bytes, copying memory area with size equal the lesser of the new and the old sizes, and freeing the old block." Therefore, there is no guarantee that the memory still exists atptr
/old_original
, and should instead be copied fromoriginal
.
https://en.cppreference.com/w/cpp/memory/c/realloc
Also added an additional condition that alignment <= 128
. Although a byte can store a maximum offset of 255
, 128
is the largest such power of two. If this becomes insufficient, we can set aside two bytes for the offset with a little more effort.
Additional information
Edited by Charles Schlosser