AnsweredAssumed Answered

[Warning] dereferencing type-punned pointer will break strict-aliasing rules [stm32f0xx_hal_crc.c]

Question asked by Valentin on Oct 30, 2016
Latest reply on Oct 7, 2017 by Clive One
This is what I get when compiling an empty created CubeMX project (CubeMX 4.17.0, STM32F0 lib v1.6.0) with the CRC module enabled.

File: stm32f0xx_hal_crc.c, affected lines:
470 -> *(uint16_t*) (&hcrc->Instance->DR) = ((uint16_t)pBuffer[4*i]<<8) | (uint16_t)pBuffer[4*i+1];
474 -> *(uint16_t*) (&hcrc->Instance->DR) = ((uint16_t)pBuffer[4*i]<<8) | (uint16_t)pBuffer[4*i+1];
506 -> *(uint16_t*) (&hcrc->Instance->DR) = pBuffer[2*i];

According to some googling, those pointers are accessing the memory of DR while interpreting it as uint16_t while DR originally is defined as uint32_t. This breaks the aliasing rules and should be avoided.

See:
here
and:
here

So changing the *(uint16_t*) to *(uint32_t*) fixes the warnings (as &hcrc->Instance->DR is of type uint32_t, not uint16_t).

See definition in stm32f042x6.h:
typedef struct
{
  __IO uint32_t DR;          /*!< CRC Data register,                           Address offset: 0x00 */
  __IO uint8_t  IDR;         /*!< CRC Independent data register,               Address offset: 0x04 */
  uint8_t       RESERVED0;   /*!< Reserved,                                                    0x05 */
  uint16_t      RESERVED1;   /*!< Reserved,                                                    0x06 */
  __IO uint32_t CR;          /*!< CRC Control register,                        Address offset: 0x08 */
  uint32_t      RESERVED2;   /*!< Reserved,                                                    0x0C */
  __IO uint32_t INIT;        /*!< Initial CRC value register,                  Address offset: 0x10 */
  __IO uint32_t RESERVED3;   /*!< Reserved,                                                    0x14 */
} CRC_TypeDef;

If the lines have to use uint16_t, though (for whatever reason) a union has been suggested.
So, ST please fix this as I don't really like the possibility of undefined behaviour and therefore hard to fix bugs in my projects.

thanks!

Outcomes