Skip to content

Using StackFallbackAllocator.get() multiple times is a footgun. #16344

@IntegratedQuantum

Description

@IntegratedQuantum

Zig Version

0.11.0-dev.3910+689f3163a

Steps to Reproduce and Observed Behavior

Calling StackFallbackAllocator.get() (re-)initializes the internal FixedBufferAllocator.
This means that calling StackFallbackAllocator.get() multiple times causes problematic behavior:

const std = @import("std");

pub fn main() !void {
	var allocator = std.heap.stackFallback(4096, std.heap.page_allocator);
	const a = try allocator.get().alloc(u8, 1);
	const b = try allocator.get().alloc(u8, 1);
	std.debug.assert(a.ptr != b.ptr);
}

This causes an assertion failure, meaning that both allocations returned the same pointer.
In actual code this is hard to debug because it leads to weird behavior.
For example in my code it messed up line wrapping and swallowed characters in text rendering.

Expected Behavior

The other allocators allow calling .allocator() multiple times without causing any trouble.
I think this should also apply to StackFallbackAllocator.get().

I think the internal FixedBufferAllocator should be initialized only once, preferably in the heap.stackFallback(..) function.

Note: This would be a breaking change, that's why I'm hesitant to implement this myself. Existing code might be relying on StackFallbackAllocator.get() to initialize the FixedBufferAllocator

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstandard libraryThis issue involves writing Zig code for the standard library.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions