Search code examples
c++qtqbytearraybad-alloc

Qt : How to debug a bad alloc exception in QByteArray?


I have a QNetworkReply and I want to store the downloaded bytes in a QByteArray.

connect(_replyRef, SIGNAL(readyRead()), this, SLOT(PushDownloadedBytesToFile()));
void PushDownloadedBytesToFile()
{
     _internalBufferBytes.append(_replyRef->readAll());
}

The problem is that I get a bad alloc when the size is approximately 33552950.

I do not understand what is the problem or how can I debug this.


Solution

  • From you comment, regarding maintaining 40 MB in buffer, I'd suggest to reserve this much memory (more would be better) in advance using QByteArray::reserve() API. But, with QByteArray, you have to maintain the total size, consumed size, current index, etc.

    Another solution could be to use QString with reserve(). You wouldn't have to maintain the details. You can simply use QString::append() and then convert it to QByteArray using QString::toUtf8() whenever you need it.