PDA

View Full Version : memcpy not working properly



sattu
26th October 2010, 07:43
hi everyone!
I am using the statement memcpy inside a function with the following code:

void extract(QByteArray buffer,unsigned long *number)
{
QByteArray byte;
byte = buffer;
memcpy(number,byte,sizeof(unsigned long));
}


when the function is called for the first time, the memcpy works fine. But it doesnot work from next time onwards. So, can any one please help me regarding this problem? what modifications are required to it or is there any other alternative to it? :(


advance thank you,

thrall
26th October 2010, 08:37
You copy the data representation of the class QByteArray to long. You can not know how it is implemented (unless you look into source code) and you can not handle the problem of possible changes to QByteArray implementation in later releases.
You also dont know wheter QByteArray contains enough bytes to read from. You should check that in extract():

sizeof(*number) <= buffer.size()

Now what you really might have wanted was copying the data contained in QByteArray. Right?
Then you might either copy the bytes by yourself, using byte[]. Here some untested code for that:

for (int i = 0; i < buffer.size(); ++i)
{
(char*)number[i] = buffer[i];
}

Or you convert QByteArray into normal C-Array and use that with memcpy:

memcpy(number,buffer.data(),sizeof(*number));

wysota
26th October 2010, 09:15
QByteArray is an implicitly shared object so the data it holds is not really inside the QByteArray structure so even copying the object would not really copy any of its data.

ChrisW67
26th October 2010, 23:33
It strikes me that, even if this did what you think it does, it would not do anything useful. The memcpy() works every time you call it and will dutifully overwrite the first bytes of the local QByteArray data structure (byte). The QByteArray byte goes out of scope and is destroyed on the next line. QByteArray buffer will remain unchanged outside the function partly because you are working on a copy inside the function, and partly because the pass-by-value semantics guarantee this.

Perhaps you meant something like:


#include <QtCore>
#include <QDebug>

void extract(QByteArray &buffer, unsigned long *number)
{
// reserve enough room for the bytes of number
buffer.resize(sizeof(unsigned long));
// get a temporary pointer to the byte array data buffer
char *data = buffer.data();
// copy
memcpy(data, number, sizeof(unsigned long));
}

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);

QByteArray ba;
unsigned long number = 0x12345678;
qDebug() << ba.size() << ba.toHex();
for (int i=0; i<8; ++i) {
extract(ba, &number);
qDebug() << ba.size() << ba.toHex();
number <<= 4;
}
}