Skip to main content
FErma
Associate II
March 25, 2020
Solved

When assigning a pointer to structure pointer, mcu goes in to Hardfault Handler.

  • March 25, 2020
  • 3 replies
  • 2946 views

Hi Everyone,

When I send a structure pointer as an agument to a function, and trying to catch address of a variable in the structure in the function, MCU goes in to hardfault handler function. Let me simplify the problem as below,

uint8_t *ptr1;

uint32_t *ptr2;

uint32_t temp;

typedef struct{

 uint8_t         Data[10];

}example_struct;

example_struct sensor;

sensor.Data[0] = 0xAA;

ptr1 = &sensor.Data[0]; // here ptr1 is pointing 0xAA with no problem

ptr2 = (uint32_t*) ptr1; // here *ptr2 is 0x000000AA, so there is no problem.

temp = *ptr2; // here mcu goes in to hardfault handler

Do you have any idea why I am having this issue?

Thanks

    This topic has been closed for replies.
    Best answer by TDK

    There is no support for unaligned accesses on the Cortex-M0 processor.

    0x200000C9 is not divisible by 4

    You'll need to read the value as 4 bytes and reconstruct the uint32_t from those.

    3 replies

    KnarfB
    Super User
    March 25, 2020

    No, your code works on my board as expected.

    TDK
    Super User
    March 25, 2020

    You're trying to read a word at a non-word aligned address. It may or may not work depending on your architecture. You don't specify what chip you're using.

    "If you feel a post has answered your question, please click ""Accept as Solution""."
    FErma
    FErmaAuthor
    Associate II
    March 25, 2020

    @KnarfB​  @TDK​ 

    Sorry for missing info. I am working on STM32F072 and using IAR as compiler.

    Let me give you details step by step;

    The address of sensor.Data[0] in the SRAM is 0x200000C9

    I can see in the live watch ptr1 is 0x200000C9 and its value is 0xAA as expected.

    ptr2 also has address of 0x200000C9, and its value is 0x000000AA as expected.

    but when I try to use the value of *ptr2 it always goes to hardfault handler.

    When I assign the address of 0x200000C9 to ptr1 manually (ptr1 = (uint8_t*) 0x200000C9) every thing works fine.

    Do you have any idea?

    FErma
    FErmaAuthor
    Associate II
    March 25, 2020

    @KnarfB​ @TDK​ 

    I just noticed, when I modify code as below, also problem is disappears.

    sensor.Data[0] = 0xAA;

    ptr1 = &sensor.Data[0]; // here ptr1 is pointing 0xAA with no problem

    // ptr2 = (uint32_t*) ptr1; // this part causes the problem. I am using this part to convert 8-bit data variable to 32-bit variable.

    temp = *ptr1;