2

Hello trying to understand, why copying byte array to not aligned structure byte by byte i loose some data. Maybe there is a way how to solve it ?

enter image description here

Sample code bellow:

typedef struct {  //Not aligned data
    uint32_t val0;
    uint8_t  val1; 
    uint16_t val2;
    uint32_t val3;
}TestSt_t; 

TestSt_t testSt;
uint8_t testData[16] =  {
    0x11, 0x22, 0x33, 0x44,
    0x55,
    0x66, 0x77,
    0x88, 0x99, 0xAA, 0xBB
};
int main() {
    memcpy((uint8_t*)&testSt, (uint8_t*)&testData[0], sizeof(testSt));
}

enter image description here

1
  • It is lost in padding: sizeof(TestSt_t) is 12, not 11. Commented Dec 1, 2019 at 9:36

1 Answer 1

2

The compiler is adding a byte of padding

typedef struct {  //Not aligned data
    uint32_t val0;
    uint8_t  val1; 
        uint8_t padding;
    uint16_t val2;
    uint32_t val3;
}TestSt_t; 

So 0x66 is in that padding byte.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to get a warning or error if compiler adds padding bytes ?
In GCC there is -Wpadded. I bet there must be something similar for VS: learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.