Reserve First

https://news.ycombinator.com/rss Hits: 2
Summary

Reserve First Aug 16, 2025 A short post about a coding pattern that is relevant for people who use the heap liberally and manage memory with their own hands. Let’s start with two bugs. The first one is from Andrew Kelley’s HYTRADBOI 2025 talk, “Programming Without Pointers”: pub fn internString( state: *State, gpa: Allocator, bytes: []const u8, ) !String { const gop = try state.string_table.getOrPutContextAdapted( gpa, @as([]const u8, bytes), @as(String.TableIndexAdapter, .{ .bytes = state.string_bytes.items, }), @as(String.TableContext, .{ .bytes = state.string_bytes.items, }), ); if (gop.found_existing) return gop.key_ptr.*; try state.string_bytes.ensureUnusedCapacity(gpa, bytes.len + 1); const new_off: String = @enumFromInt(state.string_bytes.items.len); state.string_bytes.appendSliceAssumeCapacity(bytes); state.string_bytes.appendAssumeCapacity(0); gop.key_ptr.* = new_off; return new_off; } The second one is from the Ghostty terminal emulator: pub fn grow( self: *Atlas, alloc: Allocator, size_new: u32, ) Allocator.Error!void { assert(size_new >= self.size); if (size_new == self.size) return; const data_old = self.data; const size_old = self.size; self.data = try alloc.alloc(u8, size_new * size_new * self.format.depth()); defer alloc.free(data_old); errdefer { alloc.free(self.data); self.data = data_old; } try self.nodes.append(alloc, .{ .x = size_old - 1, .y = 1, .width = size_new - size_old, }); self.size = size_new; @memset(self.data, 0); self.set(.{ .x = 0, .y = 1, .width = size_old, .height = size_old - 2, }, data_old[size_old * self.format.depth() ..]); _ = self.modified.fetchAdd(1, .monotonic); _ = self.resized.fetchAdd(1, .monotonic); } Can you spot the two bugs? In lieu of a spoiler, allow me to waste your bandwidth with a Dante Gabriel Rossetti painting: In both functions, a bug happens when the second try expression throws. In the internString case, we insert an item into a hash table, but leave it uninitialized. Accessing the item later will crash in ...

First seen: 2025-08-23 19:41

Last seen: 2025-08-23 20:43