gpt4 book ai didi

c++ - 将二进制字节 (char*) 转换为 uint64_t*,安全吗?

转载 作者:行者123 更新时间:2023-11-28 01:39:13 25 4
gpt4 key购买 nike

我正在编写从远程服务器接收包的 C++ 代码。由于事先不知道包的大小,代码首先接收 8 个字节,告诉整个包的大小。然后它分配一个足够大的缓冲区并将整个包接收到缓冲区中。

我的问题是从 const char*uint64_t* 部分的转换:转换指针然后将内容读取为 uint64_t< 是否安全?如果 buf 没有对齐到 8 字节怎么办?

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);

最佳答案

嗯,一般来说,这不应该是正确的,但在一种情况下,它可能有效,这取决于从发件人传递的实际参数的类型。

换句话说,如果发送方正在发送指向 uint64_t 类型的指针,只有在这种情况下,代码才可接受。

引用 C11,章节 §6.3.2.3

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned68) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

关于c++ - 将二进制字节 (char*) 转换为 uint64_t*,安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48056908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com