QMap: fix UB (invalid cast) in QMapData::end()

The end() pointer, like in all other containers, is a sentinel value
that must never be dereferenced. But unlike array-based containers,
end() in QMap is not "last element plus one", but points to a base class
of Node, not a full Node.

Therefore, the casting from QMapNodeBase to QMapNode must not be a
static_cast, reinterpret_cast is required.

libstdc++-v3's red-black tree had the exact same problem:
 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60734

Change-Id: I43f05fedf0b44314a2dafffd14b33697861ae589
Reviewed-by: Marc Mutz <marc.mutz@kdab.com>
bb10
Thiago Macieira 2017-04-07 13:12:05 -07:00
parent 07bd5a90a3
commit 75cdf654bc
1 changed files with 4 additions and 2 deletions

View File

@ -209,8 +209,10 @@ struct QMapData : public QMapDataBase
Node *root() const { return static_cast<Node *>(header.left); }
const Node *end() const { return static_cast<const Node *>(&header); }
Node *end() { return static_cast<Node *>(&header); }
// using reinterpret_cast because QMapDataBase::header is not
// actually a QMapNode.
const Node *end() const { return reinterpret_cast<const Node *>(&header); }
Node *end() { return reinterpret_cast<Node *>(&header); }
const Node *begin() const { if (root()) return static_cast<const Node*>(mostLeftNode); return end(); }
Node *begin() { if (root()) return static_cast<Node*>(mostLeftNode); return end(); }