Issue 24773 - Stable sort() invokes the destructor on uninitialized elements
Summary: Stable sort() invokes the destructor on uninitialized elements
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P1 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2024-09-20 09:04 UTC by Sönke Ludwig
Modified: 2024-10-28 13:22 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Sönke Ludwig 2024-09-20 09:04:15 UTC
The TimSort implementation creates a temporary uninitialized array for copying ranges of elements to. While this works fine for POD values, element types with an elaborate destructor/postblit/copy constructor will be invoked with uninitialized data, possibly leading to crashes or data corruption.

Test case:
---
import std.algorithm;
struct S {
    int i = 42;
    ~this() { assert(i == 42); }
}
void main()
{
    auto array = new S[](400);
    array.sort!((a, b) => false, SwapStrategy.stable);
}
---
Comment 1 Dlang Bot 2024-09-20 09:08:09 UTC
@s-ludwig created dlang/phobos pull request #9049 "Bugzilla 24773 - don't invoke destructors on uninitialized elements in stable sort" mentioning this issue:

- Bugzilla 24773 - don't invoke destructors on uninitialized elements in stable sort
  
  Uses a regular initialized temporary array when sorting elements with an elaborate assignment to avoid undefined behavior when destructors, postblits or copy constructors are invoked during the array assignment.

https://github.com/dlang/phobos/pull/9049
Comment 2 Dlang Bot 2024-09-20 11:38:37 UTC
dlang/phobos pull request #9049 "Fix Bugzilla 24773: don't invoke destructors on uninitialized elements in stable sort" was merged into master:

- cfd577b28dead189f08bdf5d2b6c94b3352d0af5 by Sönke Ludwig:
  Fix Bugzilla 24773: Don't invoke destructors on uninitialized elements in stable sort
  
  Uses a regular initialized temporary array when sorting elements with an elaborate assignment to avoid undefined behavior when destructors, postblits or copy constructors are invoked during the array assignment.

https://github.com/dlang/phobos/pull/9049
Comment 3 Dlang Bot 2024-10-28 13:22:17 UTC
dlang/phobos pull request #9076 "[stable] Cherry-pick 2 master fixes" was merged into stable:

- 9e78de4d86ec1b61cc39ed90083373bfa111ccdd by Sönke Ludwig:
  Fix Bugzilla 24773: Don't invoke destructors on uninitialized elements in stable sort
  
  Uses a regular initialized temporary array when sorting elements with an elaborate assignment to avoid undefined behavior when destructors, postblits or copy constructors are invoked during the array assignment.

https://github.com/dlang/phobos/pull/9076