I can do following thing with no errors. Why??? It is not only compile time defined memory but also it is not allocated by gpa which doesn’t give me any errors even in debug ![]()
const d: []u8 = &.{};
gpa.free(d);
spiffyk July 27, 2026, 5:09pm 2
When the memory to free has zero length, std.mem.Allocator.free is by its contract a no-op (i.e. it does nothing and just returns). It makes sense as there are literally zero bytes to free up.
Similarly, calling std.mem.Allocator.alloc with the n parameter set to 0 will return a dummy slice of length 0. It will never actually allocate anything. (see lines 295-298 here)
EDIT: This optimization also happens before any call to the allocator’s VTable, so you can be sure this holds true regardless of the particular allocator implementation.
pachde July 27, 2026, 5:32pm 3
To answer the question “why” the contract is this way:
It’s a good (DOD-style) design practice that degenerate cases should be no-ops instead of errors. Infallible is always better than fallible.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.