I have the following code for a key value store.
pub fn put(self: *Self, kvp: KeyValuePair) !void {
var buffer = self.buffer; // changing this to `const buffer = &self.buffer` works
// key_len + value_len + len('put') + space after 'put' + space after key + space after value
const full_size = kvp.key.len + kvp.value.len + 3 + 1 + 1 + 1;
try buffer.ensureUnusedCapacity(full_size);
std.log.debug("DEBUG: adding {} bytes to buffer\n", .{full_size});
buffer.appendSliceAssumeCapacity("put");
buffer.appendAssumeCapacity(' ');
buffer.appendSliceAssumeCapacity(kvp.key);
buffer.appendAssumeCapacity(' ');
buffer.appendSliceAssumeCapacity(kvp.value);
buffer.appendAssumeCapacity(' ');
std.debug.assert(buffer.items.len > 0);
}
pub fn flush(self: *Self) !void {
var file = self.file;
const buffer = self.buffer.items;
std.log.debug("DEBUG: flushing {} bytes\n", .{buffer.len});
_ = try file.write(buffer);
try file.sync();
self.buffer.clearRetainingCapacity();
}
When flush
is called, no bytes are actually written to the file and I get a memory leak detected error when the program exits. The reason for this is the var buffer = self.buffer
. My assumption is that this is making a copy of the buffer. If that is correct, why is that happening? What is actually happening with the line var buffer = self.buffer
?
Btw, self.buffer
is an ArrayList(u8)
.