[solved] Does QByteArray free memory on it's own accord?
-
Hi,
That's probably a somewhat silly question, but I am not sure about it.
I am using a "QByteArray":http://qt-project.org/doc/qt-4.8/qbytearray.html as intrnal buffer for an overloaded "QIODevice":http://qt-project.org/doc/qt-4.8/qiodevice.html. In the overwritten writeData(...) I assemble the new buffer content by allocating new memory and using memcpy(...) to copy the data that's already in the buffer and the new data to the newly allocated memory. Afterwards I use "QByteArray::setRawData(...)":http://qt-project.org/doc/qt-4.8/qbytearray.html#setRawData to set the content of my buffer to the just assembled data.
As QByteArray does not copy the data when using setRawData I can not free the allocated memory at the moment - but does QByteArray free the data it's content refers to when it is deleted?
A snippet to illustrate what code I am talking about:
@
qint64 QDropboxFile::writeData(const char *data, qint64 len)
{
qint64 new_len = _buffer->size()+len;
char *current_data = _buffer->data();#ifdef QTDROPBOX_DEBUG
qDebug() << "old content: " << _buffer->toHex() << endl;
#endifchar *new_data = new char[new_len]; // <-- allocating memory for new content memcpy(new_data, current_data, _buffer->size()); char *pNext = new_data+_buffer->size(); memcpy(pNext, data, len); _buffer->setRawData(new_data, new_len); // <-- setting buffer conetnt to new memory area
#ifdef QTDROPBOX_DEBUG
qDebug() << "new content: " << _buffer->toHex() << endl;
#endif// flush if the threshold is reached if(new_len%_bufferThreshold) flush(); return 0;
}
@ -
Since QByteArray has no way of knowing how you allocated the memory (on the stack, with new, or with malloc...), it can't free that memory itself.
Why don't you let it allocate the memory anyway ?
@qint64 QDropboxFile::writeData(const char *data, qint64 len)
{
_buffer->append(data, len);// flush if the threshold is reached or exceeded if(_buffer->size() >= _bufferThreshold) flush(); return len;
}@
-
Damn, I knew that functionality was implemented somwhere else ;)
You've got a point with using append(...) - and now that I think about it it's obvious that QByteArray can not free the memory on it's own... If you are working too long on a piece of code you miss the forest for the trees :)
Thanks for the clarification!