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

Mislab
  • 53
  • 4

1 Answers1

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.

tuket
  • 3,232
  • 1
  • 26
  • 41
  • Is it possible to get a warning or error if compiler adds padding bytes ? – Mislab Dec 01 '19 at 09:43
  • 1
    In GCC there is `-Wpadded`. I bet there must be something similar for VS: https://learn.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4820?view=vs-2019 – tuket Dec 01 '19 at 09:47