QVarLengthArray: fix off-by-size() bug in growBy()

The growBy() function takes the _increment_ of the size(), so needs to
add size() to increment for the call to realloc().

Add a test which hangs (vanilla build) or explodes (valgrind build)
without the fix.

Amends 26b227e128475da3f88a6b34921a08994bf71cf4.

Done-with: Eirik Aavitsland <eirik.aavitsland@qt.io>
Fixes: QTBUG-110412
Change-Id: I7ea91342fdcb779825c88013a3f86ba6d90ef530
Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org>
Reviewed-by: Fabian Kosmale <fabian.kosmale@qt.io>
(cherry picked from commit 51e5a2376a8a2956665ff4c3a0e86c8cd9d0847d)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Marc Mutz 2023-01-19 18:26:17 +01:00 committed by Qt Cherry-pick Bot
parent 81ed4430e4
commit da6e6861c1
2 changed files with 14 additions and 1 deletions

View File

@ -181,7 +181,7 @@ public:
}
protected:
void growBy(qsizetype prealloc, void *array, qsizetype increment)
{ reallocate_impl(prealloc, array, size(), (std::max)(size() * 2, increment)); }
{ reallocate_impl(prealloc, array, size(), (std::max)(size() * 2, size() + increment)); }
template <typename...Args>
reference emplace_back_impl(qsizetype prealloc, void *array, Args&&...args)
{

View File

@ -7,6 +7,8 @@
#include <qscopeguard.h>
#include <qscopedvaluerollback.h>
#include <algorithm>
#include <q20iterator.h>
#include <memory>
struct Tracker
@ -386,6 +388,17 @@ void tst_QVarLengthArray::appendCausingRealloc()
QVarLengthArray<float, 1> d(1);
for (int i=0; i<30; i++)
d.append(i);
// Regression test for QTBUG-110412:
constexpr qsizetype InitialCapacity = 10;
QVarLengthArray<float, InitialCapacity> d2(InitialCapacity);
std::iota(d2.begin(), d2.end(), 0.0f);
QCOMPARE_EQ(d2.size(), d2.capacity()); // by construction
float floats[1000];
std::iota(std::begin(floats), std::end(floats), InitialCapacity + 0.0f);
d2.append(floats, q20::ssize(floats));
QCOMPARE_EQ(d2.size(), q20::ssize(floats) + InitialCapacity);
QCOMPARE_GE(d2.capacity(), d2.size());
}
void tst_QVarLengthArray::appendIsStronglyExceptionSafe()