Skip to content

Fix bug in handmade_aligned_realloc

Reference issue

What does this implement/fix?

Addresses two bugs in handmade_aligned_realloc:

  1. memmove the correct number of bytes from new_size (used to be size) to min(old_size,new_size) so as to not overrun the bounds of the allocated memory. If new_size > old_size, then the array was expanded, and we need to copy the entire original array (old_size). If new_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 where new_size == old_size, as the behavior is possibly undefined (at best, this would result in a no-op anyway).
  2. If std::realloc returns a new address, the reallocation is performed by "allocating a new memory block of size new_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 at ptr/old_original, and should instead be copied from original.

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

Merge request reports

Loading