From 746114fb8a1036e5ccec88fe22e9378925d3a34a Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Fri, 11 Jun 2010 10:57:21 +0200 Subject: Avoid the incorrect usage of QScopedArrayPointer. Don't allow an array of objects stored as a base class. struct A{int a;}; struct B : public A{int b;}; A *foo = new B[2]; foo[1].a = 0; // crash due to (foo + sizeof(A)) and sizeof(A) != sizeof(B) delete [] foo; Reviewed-by: Olivier Goffart --- src/corelib/tools/qscopedpointer.h | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/corelib/tools/qscopedpointer.h b/src/corelib/tools/qscopedpointer.h index bc76a3b..e972d71 100644 --- a/src/corelib/tools/qscopedpointer.h +++ b/src/corelib/tools/qscopedpointer.h @@ -54,7 +54,7 @@ struct QScopedPointerDeleter static inline void cleanup(T *pointer) { // Enforce a complete type. - // If you get a compile error here, read the secion on forward declared + // If you get a compile error here, read the section on forward declared // classes in the QScopedPointer documentation. typedef char IsIncompleteType[ sizeof(T) ? 1 : -1 ]; (void) sizeof(IsIncompleteType); @@ -69,7 +69,7 @@ struct QScopedPointerArrayDeleter static inline void cleanup(T *pointer) { // Enforce a complete type. - // If you get a compile error here, read the secion on forward declared + // If you get a compile error here, read the section on forward declared // classes in the QScopedPointer documentation. typedef char IsIncompleteType[ sizeof(T) ? 1 : -1 ]; (void) sizeof(IsIncompleteType); @@ -186,11 +186,18 @@ template Q_INLINE_TEMPLATE void qSwap(QScopedPointer &p1, QScopedPointer &p2) { p1.swap(p2); } +namespace QtPrivate { + template struct QScopedArrayEnsureSameType; + template struct QScopedArrayEnsureSameType { typedef X* Type; }; + template struct QScopedArrayEnsureSameType { typedef X* Type; }; +} + template > class QScopedArrayPointer : public QScopedPointer { public: - explicit inline QScopedArrayPointer(T *p = 0) + template + explicit inline QScopedArrayPointer(D *p = 0, typename QtPrivate::QScopedArrayEnsureSameType::Type = 0) : QScopedPointer(p) { } @@ -206,6 +213,17 @@ public: } private: + explicit inline QScopedArrayPointer(void *p) { + // Enforce the same type. + + // If you get a compile error here, make sure you declare + // QScopedArrayPointer with the same template type as you pass to the + // constructor. See also the QScopedPointer documentation. + + // Storing a scalar array as a pointer to a different type is not + // allowed and results in undefined behavior. + } + Q_DISABLE_COPY(QScopedArrayPointer) }; -- cgit v0.12