简体   繁体   中英

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

*(int *)(data + 4);

and so on meets the alignment requirements for an int .

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

The code causes undefined behavior if any of the following assumptions are violated:

  • BYTE is char or unsigned char
  • none of your array access go out of bounds
  • 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
  • no bit patterns are invalid for int and float on your platform, OR these patterns do not appear in your array

You shouldn't return an allocated raw pointer though. Use unique_ptr .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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