Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/9.0] Fix heap corruption issue in PriorityQueue.Remove #107603

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -532,16 +532,30 @@ public bool Remove(
if (index < newSize)
{
// We're removing an element from the middle of the heap.
// Pop the last element in the collection and sift downward from the removed index.
// Pop the last element in the collection and sift from the removed index.
(TElement Element, TPriority Priority) lastNode = nodes[newSize];

if (_comparer == null)
{
MoveDownDefaultComparer(lastNode, index);
if (Comparer<TPriority>.Default.Compare(lastNode.Priority, priority) < 0)
{
MoveUpDefaultComparer(lastNode, index);
}
else
{
MoveDownDefaultComparer(lastNode, index);
}
}
else
{
MoveDownCustomComparer(lastNode, index);
if (_comparer.Compare(lastNode.Priority, priority) < 0)
{
MoveUpCustomComparer(lastNode, index);
}
else
{
MoveDownCustomComparer(lastNode, index);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,33 @@ public void PriorityQueue_EmptyCollection_Remove_ShouldReturnFalse()
Assert.Null(removedPriority);
}

[Fact]
public void PriorityQueue_LargeCollection_Remove_ShouldPreserveHeapInvariant()
{
// Regression test for https://github.com/dotnet/runtime/issues/107292

PriorityQueue<int, int> queue = new();
for (int i = 19; i >= 0; i--)
{
queue.Enqueue(i, i);
}

queue.Remove(10, out int _, out int _);

List<int> sortedValues = queue.UnorderedItems
.OrderBy(e => e.Priority)
.Select(e => e.Element)
.ToList();

List<int> dequeuedValues = new();
while (queue.Count > 0)
{
dequeuedValues.Add(queue.Dequeue());
}

Assert.Equal(sortedValues, dequeuedValues);
}

#region EnsureCapacity, TrimExcess

[Fact]
Expand Down
Loading