QDirIterator: don't crash with next() after hasNext() returned false

The typical use-case is calling hasNext() first before using next, but
the API docs say that calling next() even when hasNext() is false,
should just return an empty string.

[ChangeLog][QtCore][QDirIterator] Fixed a crash that happened if you
called next() after hasNext() had already returned false. Ideally you
should never call next() without first calling hasNext() as that could
lead to unexpected results (for example, infinite loops).

Fixes: QTBUG-130142
Change-Id: If0a8b1fe7dbd13b45793409a7a241e53c7257f24
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
(cherry picked from commit c7691842f743f568a073582c8f0cacd6ee188f98)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Ahmad Samir 2024-10-16 19:26:25 +03:00 committed by Qt Cherry-pick Bot
parent e25150ca29
commit 55a8050d1e
2 changed files with 16 additions and 0 deletions

View File

@ -103,6 +103,11 @@ public:
void advance()
{
// Match the behavior of advance() from before porting to QDirListing,
// that is, even if hasNext() returns false, calling next() returns an
// empty string without crashing. QTBUG-130142
if (it == lister.end())
return;
currentFileInfo = nextFileInfo;
if (++it != lister.end()) {
nextFileInfo = it->fileInfo();

View File

@ -86,6 +86,8 @@ private slots:
void hiddenDirs_hiddenFiles();
#endif
void hasNextFalseNoCrash();
private:
QSharedPointer<QTemporaryDir> m_dataDir;
};
@ -642,6 +644,15 @@ void tst_QDirIterator::hiddenDirs_hiddenFiles()
}
#endif // Q_OS_WIN
void tst_QDirIterator::hasNextFalseNoCrash()
{
QDirIterator iter(u"empty"_s, QDir::NoDotAndDotDot);
// QTBUG-130142
// No crash if you call next() after hasNext() returned false
QVERIFY(!iter.hasNext());
QVERIFY(iter.next().isEmpty());
}
QTEST_MAIN(tst_QDirIterator)
#include "tst_qdiriterator.moc"