[Qt-interest] On overriding qMalloc in QVector
Thiago Macieira
thiago at kde.org
Thu Oct 22 16:40:07 CEST 2009
Em Quinta-feira 22 Outubro 2009, às 16:24:41, você escreveu:
> > Already done. But that doesn't affect what qMalloc does. In our case,
> > whenever qMalloc returns a pointer that's not 16-byte aligned, we
> > crash upon the subsequent access.
>
> int sizeOfTypedData() {
> // this is more or less the same as sizeof(Data), except that it
> doesn't
> // count the padding at the end
> return reinterpret_cast<const char *>(&(reinterpret_cast<const
> Data *>(this))->array[1]) - reinterpret_cast<const char *>(this);
> }
>
I spoke too soon. I see the problem now:
#include <QVector>
#include <QDebug>
struct __attribute__((aligned(32))) MyType { int i; };
int main()
{
QVectorTypedData<MyType> *d = static_cast<QVectorTypedData<MyType>
*>(qMalloc(sizeof(*d)));
union { MyType *ptr; quintptr n; } p;
p.ptr = &d->array[0];
qDebug() << "Pointer is:" << (void*)p.ptr;
int align = 0;
while ((p.n & align) == 0)
align = (align << 1) | 1;
align >>= 1;
qDebug().nospace() << "Pointer is " << (align + 1) << "-bytes aligned";
}
Output:
$ ./vectoralign
Pointer is: 0x8e4d1c8
Pointer is 8-bytes aligned
The code causes the padding between the last item in QVectorData and array[0]
to be taken into consideration. When created on the stack, the alignment for
the entire struct is also taken into consideration.
However, when doing dynamic allocations, that isn't true. The pointer that is
returned from malloc() isn't aligned properly.
We need to pass the alignment requirements from the compiler to the allocator
function. So we need a qMallocAligned function.
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
Senior Product Manager - Nokia, Qt Development Frameworks
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20091022/ba617c57/attachment.bin
More information about the Qt-interest-old
mailing list