Improve reallocation in alloc_system on Windows #42331
Merged
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
For allocations where the alignment is greater than the alignment guaranteed by
HeapAlloc
, the implementation will overallocate byalign
bytes.align_ptr
will the get the first address within that allocation satisfying the alignment (other than the base of the allocation) and write the address of the original allocation a pointer size before that aligned address. What the offset is within any given overaligned allocation varies on a per allocation basis, which means the offset of data written to the allocation varies on a per allocation basis.The old version of
reallocate
would always callHeapRealloc
, which will move the allocation to a new address, which has the side effect of causing the aligned offset within the allocation to possibly change. Since the data itself wasn't moved to the new offset but remained at its old offset, this effectively changed the data in the allocation which is of course quite bad.The new version does exactly what the unix version does, which is to allocate a brand new buffer, figure out what the aligned address is, and then memcpy over the data from the old aligned address to the new aligned address, which works just fine.
While I was at it, I updated
reallocate_inplace
to be able to do inplace reallocations of overaligned data. Because inplace reallocation does not change the base address of the allocation, it does not change the aligned offset, therefore the data will safely remain in the same location without issue.Fixes #42025