Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: convert vector<char> to double

Tags:

c++

vector

buffer

I am using vector<char> to send and receive data via socket. In this vector I stored data of different types. Unsigned Integer and Doubles. To decode the data from vector I am using copy function.

vector<char> myVector = ... smth;
double value = 0.0;
copy(myVector.begin(), myVector.begin() + sizeof(value), &value);

It works with Integer without problem. But...

My problem is, that the compile gives out an error "free(): invalid pointer: 0x00000000006d0e30". I checked, the problem is with the double value, not with the vector. I looked the address of double value it was (0x6d0e38). Why the program tries to access the pointer backwards? I would be glad, if you can say me, what I am doing wrong. And is it the good way to decode message?

Thank you a lot.

like image 345
M.K. Avatar asked Oct 19 '25 05:10

M.K.


1 Answers

It works with Integer without problem. But...

It most certainly will not work for integers. At least not for integers where sizeof(int) > 1! Because it will not write to just one integer, but spread the bytes in myVector over sizeof(T) integers, thus overwriting random memory. (see nightcracker's answer)

Please just use memcpy for this kind of copying:

vector<char> myVector = ... smth;
double value = 0.0;
assert(myVector.size() == sizeof(double));
memcpy(&value, &myVector[0], std::min(myVector.size(), sizeof(double)));
// as an alternative to the assert + std::min() above, you could also throw
// an exception if myVector.size() == sizeof(double) does not hold.
// (that's what I'd do if the size should always match exactly)

memcpy is made exactly for that kind of thing (copying raw memory), and I see no reason to use anything else here. Using std::copy does not make it better C++, especially when you're not doing it correctly. std::copy is for copying objects, not raw memory.

like image 190
Paul Groke Avatar answered Oct 21 '25 19:10

Paul Groke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!