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.
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 inmyVectoroversizeof(T)integers, thus overwriting random memory. (see nightcracker’s answer)Please just use
memcpyfor this kind of copying:memcpyis made exactly for that kind of thing (copying raw memory), and I see no reason to use anything else here. Usingstd::copydoes not make it better C++, especially when you’re not doing it correctly.std::copyis for copying objects, not raw memory.