[Qt-interest] [Newbie question] Why string.toAscii().data() doesn't work?

Andreas Pakulat apaku at gmx.de
Thu Mar 26 12:22:42 CET 2009


On 26.03.09 12:10:59, Jesús Spí­nola wrote:
> QString testingString = "testing";
> char *data = testingString .toAscii().data();
> qDebug() << "data = " << data;
> std::cout<<"data = " << data << std::endl;
> 
> It prints garbage on data. But if I do this way:
> 
> QString testingString = "testing";
> QByteArray temp = testingString.toAscii();
> char *data = temp.data();
> qDebug() << "data = " << data;
> std::cout<<"data = " << data << std::endl;
> 
> It prints "testing" correctly.
> 
> My explanation is that on the first version the pointer returned by data()
> points to a temporally object "alive" only on the same line, so, when we
> reach the next lines the memory of this pointer is invalid.
> 
> Is this correct?

Yes, toAscii() constructs a QByteArray and returns that and
QByteArray::data() returns a pointer to its internal data structure - as
explained in the documentation. So as soon as the bytearray goes out of
scope, the memory at the address is possibly being cleared. (msvc runtime
overwrites deleted memory with garbage). 

Andreas

-- 
Lady Luck brings added income today.  Lady friend takes it away tonight.



More information about the Qt-interest-old mailing list