Skip to contentSkip to conversation

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

PATCH New Hsiu Che Yu 1 participant 1 message Apr 24

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: alloc: add test for realloc with zero size acting as free

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.

---
 rust/kernel/alloc/allocator.rs | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
rust/kernel/alloc/allocator.rs +19 -0
index 63bfb91b3671..6120587db205 100644
@@ -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(())
+    }
 }
Signature · 1 line
2.43.0