[PATCH] rust: alloc: add test for realloc with zero size acting as free

From: Hsiu Che Yu

Date: Fri Apr 24 2026 - 01:30:28 EST


The `Allocator` trait documents that reallocating with a target size of
zero must be equivalent to freeing the memory:

"If the requested size is zero, `realloc` behaves equivalent
to `free`."

Add unit test to verify that `KMalloc`, `Vmalloc`, and `KVmalloc` all
conform to this contract.

Signed-off-by: Hsiu Che Yu <yu.whisper.personal@xxxxxxxxx>
---
rust/kernel/alloc/allocator.rs | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)

diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index 63bfb91b3671..6120587db205 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -305,4 +305,23 @@ fn is_aligned_to(&self, align: usize) -> bool {

Ok(())
}
+
+ #[test]
+ fn test_realloc_zero_size_is_free() -> Result {
+ const INIT_SIZE: usize = 64;
+
+ let old = Layout::from_size_align(INIT_SIZE, 1).unwrap();
+ let new = Layout::from_size_align(0, 1).unwrap();
+
+ let ptr = unsafe { Kmalloc::realloc(None, new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+ assert_eq!(ptr.len(), 0);
+
+ let ptr = unsafe { Vmalloc::realloc(None, new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+ assert_eq!(ptr.len(), 0);
+
+ let ptr = unsafe { KVmalloc::realloc(None, new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+ assert_eq!(ptr.len(), 0);
+
+ Ok(())
+ }
}
--
2.43.0