Search code examples
cgccarmgcc-warningatmelstudio

cast increases required alignment of target type with pointer


I am working on an ARM project (SAMD21J18A) which reads a Bitmap file. Per the Bitmap specs, a bitmaps height will be a 4 byte long signed integer. In my struct, I am declaring the height as int32_t. Per the BMP specs, the height can be negative, but I also need to determine the actual height because the height's negative value can be expressed in "Two's complement" (correct me if I am wrong). To do this, I am reading the buffer like so (index 22-25 are the 4 bytes for the height)

bmp.height = *(int32_t*)&header_buff[22];

However, I receive the following compiler warning:

cast increases required alignment of target type [-Wcast-align]

I'm using the arm-none-eabi-gcc compiler.

Here is snippet of my code:

struct bitmap_t  {  
  int32_t width;
  int32_t height;       
  /* other properties left out for simplicity */
};

I am loading the first 54 bytes into a buffer to read the header:

struct bitmap_t bmp;
int8_t header_buff[54];
/* code to read the bmp here */
bmp.height = *(int32_t*)&header_buff[22];

Solution

  • If header_buff is aligned on a 4-byte boundary, then header_buff[22] is not on a 4-byte boundary. So you can't read the height like that. You need to read the bytes one at time and use shift and OR operations to recreate the height.