[Solved] QByteArray and dynamic memory



  • Hi
    Some basic understanding question:
    I know that the following gives me exactly the memory I need:
    @QByteArray * datagram;
    datagram = new(std::nothrow) QByteArray [uDataSize.l];
    @

    On other places I simply use:
    @QByteArray RawPortData;
    @

    which works as supposed (where I actually don't know how much I need at runtime).
    How much memory does Qt/++ reserve in the second case?
    Do I need to allocate with new?

    Thanks
    McL


  • Moderators

    Hi,

    [quote author="McLion" date="1390826819"]
    I know that the following gives me exactly the memory I need:
    @QByteArray * datagram;
    datagram = new(std::nothrow) QByteArray [uDataSize.l];
    @
    [/quote]No, this won't give you exactly the memory you need. This will create many empty arrays.

    [quote]On other places I simply use:
    @QByteArray RawPortData;
    @

    which works as supposed (where I actually don't know how much I need at runtime).
    How much memory does Qt/++ reserve in the second case?
    Do I need to allocate with new?[/quote]This is the correct way to use QByteArray. You should virtually never need to allocate Qt containers (QByteArray, QString, QVector, etc.) using new.

    Qt keeps track of the memory allocated. If you add more data into the array, Qt will automatically allocate more memory.

    See also http://qt-project.org/doc/qt-5/QByteArray.html



  • OK.
    Thanks a lot.


Log in to reply