I am writing this C++ code that receives packages from remote server. Since the size of the package is not known in advance, the code first receives 8 bytes which tells the size of the whole package. Then it allocates a large enough buffer and receive the whole package into the buffer.
My question is with the casting from const char*
to uint64_t*
part: is it safe to cast the pointer and then read the content as uint64_t
? What if the buf
is not aligned to 8 bytes?
const char* buf;
RecvBytes(buf, sizeof(uint64_t)); // the first 8 bytes should tell us the size of the whole package
uint64_t pkg_size = *(uint64_t*)buf; // is this safe??
const char* pkg = new char[pkg_size];
RecvBytes(pkg, pkg_size);