From 31e79901454264b4e3ad22a207bf5df9d6aef9a5 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Wed, 6 Apr 2022 01:32:26 +0530 Subject: [PATCH 1/3] fix Vec leak with 0 capacity --- library/alloc/src/raw_vec.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 0ce2beb63d681..5cf190423e399 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -170,6 +170,13 @@ impl RawVec { fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { if mem::size_of::() == 0 { Self::new_in(alloc) + } else if capacity == 0 { + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + Self { + ptr: unsafe { Unique::new_unchecked(NonNull::dangling().as_ptr()) }, + cap: capacity, + alloc, + } } else { // We avoid `unwrap_or_else` here because it bloats the amount of // LLVM IR generated. From 9e9881bcd803390bfbc1e3b1c64ad66330b01103 Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Wed, 6 Apr 2022 01:36:24 +0530 Subject: [PATCH 2/3] cleanup --- library/alloc/src/raw_vec.rs | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index 5cf190423e399..f73b3866c9cb5 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -168,15 +168,9 @@ impl RawVec { #[cfg(not(no_global_oom_handling))] fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { - if mem::size_of::() == 0 { + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + if mem::size_of::() == 0 || capacity == 0 { Self::new_in(alloc) - } else if capacity == 0 { - // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. - Self { - ptr: unsafe { Unique::new_unchecked(NonNull::dangling().as_ptr()) }, - cap: capacity, - alloc, - } } else { // We avoid `unwrap_or_else` here because it bloats the amount of // LLVM IR generated. From 83f659b4bb2212037ec62028b1979ec31d956fdd Mon Sep 17 00:00:00 2001 From: SparkyPotato Date: Wed, 6 Apr 2022 01:36:46 +0530 Subject: [PATCH 3/3] formatting --- library/alloc/src/raw_vec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index f73b3866c9cb5..9dbac3c36ffb2 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -168,7 +168,7 @@ impl RawVec { #[cfg(not(no_global_oom_handling))] fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { - // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. + // Don't allocate here because `Drop` will not deallocate when `capacity` is 0. if mem::size_of::() == 0 || capacity == 0 { Self::new_in(alloc) } else {