From 20b6e5c2fdb6e3ae2eb5403aee256ad51f12fa46 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 25 Dec 2024 14:02:49 +0100 Subject: [PATCH] Prevent double-free in rb_destroy --- ringbuf.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/ringbuf.c b/ringbuf.c index d73affe..ffc979e 100644 --- a/ringbuf.c +++ b/ringbuf.c @@ -29,7 +29,18 @@ rb_init(struct RingBuf *rb, rb_size_t capacity, ALLOC_T malloc_fn, void rb_destroy(struct RingBuf *rb, FREE_T free_fn) { - free_fn(rb->buffer); + if(rb->buffer) { // Prevent double-free + free_fn(rb->buffer); + rb->buffer = NULL; + rb->buffer_end = NULL; + + rb->struct_size = 0; + rb->capacity = 0; + rb->count = 0; + + rb->write_head = NULL; + rb->read_head = NULL; + } } void @@ -46,6 +57,8 @@ rb_push_back(struct RingBuf *rb, const void *item, MEMCPY_T memcpy_fn) if(rb->count == rb->capacity) return Full; + assert(rb->buffer != NULL); + memcpy_fn(rb->write_head, item, rb->struct_size); // Advance the write head