-1

My question today is about Qt and the memcpy() function.. I got a QByteArray i_byte_array containing my raw data that I need. First thing I tried is to copy those data in a char* l_array. Which gives me:

void blablafunctionblabla(const QByteArray& i_byte_array)
{
   char* l_array = (char*)malloc(i_byte_array.size());
   memcpy(l_array, i_byte_array, i_byte_array.size());
   // OR: char* l_array = i_byte_array.data(); // same result
}

When I run the code I expected to copy the whole contents of i_byte_array which is: i_byte_array values

As a result I get only this...: l_array value

It seems the copying stopped at the first /0 ignoring the size I request him to copy..

So my questions is Why that happens with memcpy function? And How do I need to proceed in order to copy all raw data? (even /0 which is a useful data for me)

SquadOne
  • 3
  • 4
  • `char* l_array = i_byte_array.data();` not really copying anything except for a pointer here – Big Temp Jun 17 '20 at 00:52
  • memcpy(l_array, i_byte_array.data(), i_byte_array.size()); – pm100 Jun 17 '20 at 00:54
  • 3
    As a C++ programmer, you shouldn't immediately reach for `C` functions such as `malloc` and `memcpy` -- Using `std::copy` using the arguments you had for `memcpy` would not have compiled, thus preventing you from making this mistake at runtime. Also, what is the reason for wanting to create another buffer, when you have the data already sitting in the `i_byte_array`? – PaulMcKenzie Jun 17 '20 at 00:57
  • @BigTemp : Yes you right, sorry. but even here I didn't get other value after \0.. I thought memcpy() didn't care about this character.. – SquadOne Jun 17 '20 at 07:59
  • @pm100 : Thank you for your answer, I try what you said but same result :/ – SquadOne Jun 17 '20 at 08:05
  • @PaulMcKenzie : Yes you're right, it's my old reflex from C embedded development.. And I will try with std::cpy instead. For your understanding, what I do it's just a copy test. My final purpose it's to parse that Byte array adjusting the size in the memcpy. For the moment I try to copy the whole array – SquadOne Jun 17 '20 at 08:13

1 Answers1

0

Actually memcpy does not ignore the null character. I guess the IDE (maybe Qt Creator) ignores the null character so you can't see the entire content of the char string.

If you import the l_array to a QByteArray by the following way:

QByteArray ba = QByteArray::fromRawData(l_array, i_byte_array.size());

You will see the content of ba is the same as i_byte_array.

You can check SO's question for the memcpy: How could I copy data that contain '\0' character.

wthung
  • 167
  • 2
  • 12
  • Yes, thank you @wthung for your answer. It's just a Qt Creator issue, when I look into the memory before and after the copy I can see that the whole byte array is copied. Even if Qt Creator stop its display at the first '\0'. Conclusion: memcpy works fine and I can parse the array with :) – SquadOne Jun 19 '20 at 18:21