From d8134361c95115ec2dd00c9c31a0e1e8f9d8b671 Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Mon, 30 Dec 2024 23:08:28 +0100 Subject: [PATCH] struct: fix memory leak in buffer.pull() Do not increase the refcount when returning the pulled buffer contents as string since the returned value already is the sole reference. Without this change, pulled buffer contents will be leaked whenever the `pull()` function is used. Also ensure that the buffer memory is completely zero initialized when it is allocated from scratch, the existing logic only cleared the trailing data area on reallocations but never the head on fresh allocations. Signed-off-by: Jo-Philipp Wich --- lib/struct.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/struct.c b/lib/struct.c index 7c039f24..73933473 100644 --- a/lib/struct.c +++ b/lib/struct.c @@ -2514,7 +2514,10 @@ grow_buffer(uc_vm_t *vm, void **buf, size_t *bufsz, size_t length) return false; } - memset(tmp + overhead + old_size - 1, 0, new_size - old_size + 1); + if (*buf) + memset(tmp + overhead + old_size - 1, 0, new_size - old_size + 1); + else + memset(tmp, 0, new_size + overhead); *buf = tmp; *bufsz = new_size; @@ -3655,7 +3658,7 @@ uc_fmtbuf_pull(uc_vm_t *vm, size_t nargs) buffer->position = 0; buffer->length = 0; - return ucv_get(&us->header); + return &us->header; }