@@ -530,6 +530,12 @@ pub unsafe fn zeroed<T>() -> T {
530
530
/// it goes out of scope (and therefore would be dropped). Note that this
531
531
/// includes a `panic` occurring and unwinding the stack suddenly.
532
532
///
533
+ /// If you partially initialize an array, you may need to use
534
+ /// [`ptr::drop_in_place`][drop_in_place] to remove the elements you have fully
535
+ /// initialized followed by [`mem::forget`][mem_forget] to prevent drop running
536
+ /// on the array. If a partially allocated array is dropped this will lead to
537
+ /// undefined behaviour.
538
+ ///
533
539
/// # Examples
534
540
///
535
541
/// Here's how to safely initialize an array of [`Vec`]s.
@@ -583,11 +589,44 @@ pub unsafe fn zeroed<T>() -> T {
583
589
/// println!("{:?}", &data[0]);
584
590
/// ```
585
591
///
592
+ /// This example shows how to handle partially initialized arrays, which could
593
+ /// be found in low-level datastructures.
594
+ ///
595
+ /// ```
596
+ /// use std::mem;
597
+ /// use std::ptr;
598
+ ///
599
+ /// // Count the number of elements we have assigned.
600
+ /// let mut data_len: usize = 0;
601
+ /// let mut data: [String; 1000];
602
+ ///
603
+ /// unsafe {
604
+ /// data = mem::uninitialized();
605
+ ///
606
+ /// for elem in &mut data[0..500] {
607
+ /// ptr::write(elem, String::from("hello"));
608
+ /// data_len += 1;
609
+ /// }
610
+ ///
611
+ /// // For each item in the array, drop if we allocated it.
612
+ /// for i in &mut data[0..data_len] {
613
+ /// ptr::drop_in_place(i);
614
+ /// }
615
+ /// }
616
+ /// // Forget the data. If this is allowed to drop, you may see a crash such as:
617
+ /// // 'mem_uninit_test(2457,0x7fffb55dd380) malloc: *** error for object
618
+ /// // 0x7ff3b8402920: pointer being freed was not allocated'
619
+ /// mem::forget(data);
620
+ /// ```
621
+ ///
586
622
/// [`Vec`]: ../../std/vec/struct.Vec.html
587
623
/// [`vec!`]: ../../std/macro.vec.html
588
624
/// [`Clone`]: ../../std/clone/trait.Clone.html
589
625
/// [ub]: ../../reference/behavior-considered-undefined.html
590
626
/// [write]: ../ptr/fn.write.html
627
+ /// [drop_in_place]: ../ptr/fn.drop_in_place.html
628
+ /// [mem_zeroed]: fn.zeroed.html
629
+ /// [mem_forget]: fn.forget.html
591
630
/// [copy]: ../intrinsics/fn.copy.html
592
631
/// [copy_no]: ../intrinsics/fn.copy_nonoverlapping.html
593
632
/// [`Drop`]: ../ops/trait.Drop.html
0 commit comments