reftable: fix unlikely leak on API error

If the reftable writer sees a bogus block size, we return with REFTABLE_API_ERROR, leaking the reftable_writer struct we previously allocated. Originally this case was a BUG(), but it became a regular return in 445f9f4f35 (reftable: stop using `BUG()` in trivial cases, 2025-02-18). We could obviously fix it by calling "reftable_free(wp)". But we can observe that we never use the allocated "wp" until after we've validated the input options. So let's just bump the allocation down. That fixes the leak, and I think makes the flow of the function more logical (we validate our inputs before doing any work). Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Jun 28, 2026 at 05:03 UTC c6fb3b9c3ec6ca16ba2fbed154b41b22e5a088f0
1 file changed +4 -4
reftable/writer.c
+4 -4
@@ -152,16 +152,16 @@ int reftable_writer_new(struct reftable_writer **out,
152 struct reftable_write_options opts = {0};
153 struct reftable_writer *wp;
154
155 - wp = reftable_calloc(1, sizeof(*wp));
156 - if (!wp)
157 - return REFTABLE_OUT_OF_MEMORY_ERROR;
158 -
155 if (_opts)
156 opts = *_opts;
157 options_set_defaults(&opts);
158 if (opts.block_size >= (1 << 24))
159 return REFTABLE_API_ERROR;
160
161 + wp = reftable_calloc(1, sizeof(*wp));
162 + if (!wp)
163 + return REFTABLE_OUT_OF_MEMORY_ERROR;
164 +
165 reftable_buf_init(&wp->block_writer_data.last_key);
166 reftable_buf_init(&wp->last_key);
167 reftable_buf_init(&wp->scratch);