From 2efa206862c05b3aaf9b2e017543bb320da883cf Mon Sep 17 00:00:00 2001 From: Emily Matheys Date: Tue, 24 Feb 2026 16:37:54 +0200 Subject: [PATCH] fix: alloc(0) call is UB --- src/lib.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5a3051ac..f449fb42 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1051,6 +1051,15 @@ impl AlignedBuf { /// Creates a new buffer that is aligned with the simd register size #[must_use] pub fn with_capacity(capacity: usize) -> Self { + if capacity == 0 { + let layout = Layout::from_size_align(0, SIMDJSON_PADDING).unwrap(); + return Self { + layout, + capacity: 0, + len: 0, + inner: NonNull::dangling(), + }; + } let Ok(layout) = Layout::from_size_align(capacity, SIMDJSON_PADDING) else { Self::capacity_overflow() }; @@ -1092,8 +1101,10 @@ impl AlignedBuf { } impl Drop for AlignedBuf { fn drop(&mut self) { - unsafe { - dealloc(self.inner.as_ptr(), self.layout); + if self.capacity > 0 { + unsafe { + dealloc(self.inner.as_ptr(), self.layout); + } } } }