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

<deque>: Add missed masking of _First_used_block_idx in deque::shrink_to_fit to correctly end the loop #4955

Merged
merged 2 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 4 additions & 2 deletions stl/inc/deque
Original file line number Diff line number Diff line change
Expand Up @@ -997,7 +997,8 @@ public:

const auto _Mask = static_cast<size_type>(_Mapsize() - 1);

const auto _First_used_block_idx = static_cast<size_type>(_Myoff() / _Block_size);
const auto _Unmasked_first_used_block_idx = static_cast<size_type>(_Myoff() / _Block_size);
const auto _First_used_block_idx = static_cast<size_type>(_Unmasked_first_used_block_idx & _Mask);

// (_Myoff() + _Mysize() - 1) is for the last element, i.e. the back() of the deque.
// Divide by _Block_size to get the unmasked index of the last used block.
Expand All @@ -1017,7 +1018,8 @@ public:
}
}

const auto _Used_block_count = static_cast<size_type>(_Unmasked_first_unused_block_idx - _First_used_block_idx);
const auto _Used_block_count =
static_cast<size_type>(_Unmasked_first_unused_block_idx - _Unmasked_first_used_block_idx);

size_type _New_block_count = _Minimum_map_size; // should be power of 2

Expand Down
25 changes: 25 additions & 0 deletions tests/std/tests/GH_002769_handle_deque_block_pointers/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <deque>
#include <iterator>
#include <memory>
Expand Down Expand Up @@ -328,8 +329,32 @@ void test_inconsistent_difference_types() {
assert(counter == 0);
}

// Also test GH-4954: Endless loop in deque::shrink_to_fit()
void test_gh_4954() {
deque<int> qu;

int it = 0;
while (it < 1024) {
frederick-vs-ja marked this conversation as resolved.
Show resolved Hide resolved
const auto numAlloc = static_cast<size_t>(rand() + 1);
frederick-vs-ja marked this conversation as resolved.
Show resolved Hide resolved
for (size_t i = 0; i < numAlloc; i++) {
frederick-vs-ja marked this conversation as resolved.
Show resolved Hide resolved
qu.push_back(0);
}

auto numDealloc = static_cast<size_t>(rand() + 1);
if (it % 100 == 0 || numDealloc > qu.size()) {
numDealloc = qu.size();
}
for (size_t i = 0; i < numDealloc; i++) {
qu.pop_front();
}
qu.shrink_to_fit();
++it;
}
}

int main() {
test_gh_2769();
test_gh_3717();
test_gh_4954();
test_inconsistent_difference_types();
}