简体   繁体   English

C++ 这个 function 会导致未定义的行为吗?

[英]C++ does this function cause a undefined behavior?

Hello i think this is causing an undefined behavior but not sure您好,我认为这会导致未定义的行为,但不确定

PlayerMoving *unpackPlayerMoving(BYTE *data)
{
    PlayerMoving *dataStruct = new PlayerMoving;
    dataStruct->packetType = *(int *)(data);
    dataStruct->netID = *(int *)(data + 4);
    dataStruct->characterState = *(int *)(data + 12);
    dataStruct->plantingTree = *(int *)(data + 20);
    dataStruct->x = *(float *)(data + 24);
    dataStruct->y = *(float *)(data + 28);
    dataStruct->XSpeed = *(float *)(data + 32);
    dataStruct->YSpeed = *(float *)(data + 36);
    dataStruct->punchX = *(int *)(data + 44);
    dataStruct->punchY = *(int *)(data + 48);
    return dataStruct;
}

does it cause it and if it does how could i fix it?它会导致它吗?如果它会导致它,我该如何解决它?

this is playermoving这是玩家移动

struct PlayerMoving
{
    int packetType;
    int netID;
    float x;
    float y;
    int characterState;
    int plantingTree;
    float XSpeed;
    float YSpeed;
    int punchX;
    int punchY;
    int secondnetID;
};

and byte is和字节是

typedef unsigned char BYTE;

The behaviour of your code is undefined.您的代码的行为未定义。

Even if BYTE is an unsigned char type ( unsigned char is an exception to the strict aliasing rule), there is no guarantee that即使BYTEunsigned char类型( unsigned char是严格别名规则的例外),也不能保证

*(int *)(data + 4);

and so on meets the alignment requirements for an int .等等符合int的 alignment 要求。

Your best bet is to memcpy the data from the BYTE array to each structure member, and trust the compiler to optimise (check the generated assembly).您最好的选择是将BYTE数组中的数据memcpy到每个结构成员,并相信编译器会进行优化(检查生成的程序集)。

The code causes undefined behavior if any of the following assumptions are violated:如果违反以下任何假设,代码将导致未定义的行为:

  • BYTE is char or unsigned char BYTEcharunsigned char
  • none of your array access go out of bounds您的阵列都没有访问 go 越界
  • your implementation allows unaligned accesses, OR the required alignments of int and float do not exceed 4 bytes AND your array starts at an appropriately aligned address您的实现允许未对齐的访问,或者intfloat所需的对齐不超过 4 个字节并且您的数组从适当对齐的地址开始
  • no bit patterns are invalid for int and float on your platform, OR these patterns do not appear in your array没有位模式对int无效并且在您的平台上float ,或者这些模式不会出现在您的数组中

You shouldn't return an allocated raw pointer though.但是,您不应该返回分配的原始指针。 Use unique_ptr .使用unique_ptr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM