ArrayList.toOwnedSlice assertion error with zero-sized types #22483
Labels
bug
Observed behavior contradicts documented or intended behavior
contributor friendly
This issue is limited in scope and/or knowledge of Zig internals.
standard library
This issue involves writing Zig code for the standard library.
Milestone
Zig Version
0.14.0-dev.2613+0bf44c309
Description
Calling
ArrayList.toOwnedSlice()
with a zero-sized type triggers an assertion error in the allocator's resize implementation when using certain allocators.Steps to Reproduce
Minimal Example
Observed Behavior
The program panics with an assertion error when calling
toOwnedSlice()
.Stack Trace
Allocator-Specific Behavior
std.heap.GeneralPurposeAllocator
std.heap.FixedBufferAllocator
std.heap.page_allocator
std.heap.ArenaAllocator
(with any underlying allocator including GPA, page_allocator, and FixedBufferAllocator)Expected Behavior
The program should complete without any assertion errors and print:
Technical Analysis
Zero-Sized Type Behavior
Foo
(@sizeOf(Foo)
) is 0Foo
have a conceptual length but occupy no actual memory, which leads to mismatch described below:Implementation Details
toOwnedSlice
callsallocator.resize(old_memory, self.items.len)
to attempt an in-place resizeAllocator.resize
,mem.sliceAsBytes
is called to convert the slice to bytes:sliceAsBytes
function has special handling for zero-sized types:Allocator.rawResize
to the allocator's vtable implementationRoot Cause
std.ArrayList.toOwnedSlice
does not account for zero-sized types correctly, resulting in an invalid call toallocator.resize
. The mismatch between the conceptual length of the zero-sized type slice and the actual byte slice length leads to the assertion failure.Proposed solution
Since zero-sized types require no actual memory allocation, we can short-circuit the resize operation for them. Here's my proposed modification to toOwnedSlice:
This:
The text was updated successfully, but these errors were encountered: