Bug 24773 – Stable sort() invokes the destructor on uninitialized elements
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2024-09-20T09:04:15Z
Last change time
2024-10-28T13:22:17Z
Assigned to
No Owner
Creator
Sönke Ludwig
Comments
Comment #0 by sludwig — 2024-09-20T09:04:15Z
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 by dlang-bot — 2024-09-20T09:08:09Z
@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 by dlang-bot — 2024-09-20T11:38:37Z
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 by dlang-bot — 2024-10-28T13:22:17Z
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