From 01b5b06874591dde9c5caa3406e6f59a4eb96d64 Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Mon, 2 Feb 2026 23:42:11 +0100 Subject: [PATCH] Assert that index is valid in wxArray::operator[] Restore compatibility with all the previous wxWidgets versions that had this assert and make sure that errors in the code using this operator don't go unnoticed, as it happened with #26148. Closes #26149. --- include/wx/dynarray.h | 12 ++++++++++++ tests/arrays/arrays.cpp | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/include/wx/dynarray.h b/include/wx/dynarray.h index afd25b7e68..611655e602 100644 --- a/include/wx/dynarray.h +++ b/include/wx/dynarray.h @@ -122,6 +122,18 @@ public: bool IsEmpty() const { return this->empty(); } size_t Count() const { return this->size(); } + T& operator[](size_t uiIndex) + { + wxASSERT( uiIndex < this->size() ); + return base_vec::operator[](uiIndex); + } + + const T& operator[](size_t uiIndex) const + { + wxASSERT( uiIndex < this->size() ); + return base_vec::operator[](uiIndex); + } + T& Item(size_t uiIndex) const { wxASSERT( uiIndex < this->size() ); diff --git a/tests/arrays/arrays.cpp b/tests/arrays/arrays.cpp index 5875c4f1ad..3ada06fb64 100644 --- a/tests/arrays/arrays.cpp +++ b/tests/arrays/arrays.cpp @@ -321,6 +321,11 @@ TEST_CASE("wxArrayString", "[dynarray]") CHECK( a5.size() == 3 ); CHECK( a5[2] == "Foo" ); + // This is undefined behaviour but because the array has just been resized + // down, its memory hopefully hasn't been reallocated yet, so we shouldn't + // crash accessing it. But we must assert due to the index being invalid. + WX_ASSERT_FAILS_WITH_ASSERT( a5[3].clear() ); + wxArrayString a6; a6.Add("Foo"); a6.Insert(a6[0], 1, 100);