Pointer casting problem in C with Atollic TrueSTUDIO for STM32 IDE

131 views Asked by At

Working on STM32H7 in Atollic TrueSTUDIO for STM32 IDE. Only C coding. Using FreeRTOS.

Ui08 *pointerSomething;
Ui64 localVariable;

pointerSomething=&addressOfSomething;
localVariable = *(Ui64*)(pointerSomething);

These code is generally working.

But one of my usage in a case in a thread in something like that;

thread begin //

Ui08 *pointerSomething;
Ui64 localVariable;

case 3: 

   pointerSomething=&addressOfSomething;
   localVariable = *(Ui64*)(pointerSomething);

break;

thread end //

And I am getting a hardfault when the second sequence in these case. I mean first time in case working properly but second time in case getting hardfault exactly the line of localVariable = *(Ui64*)(pointerSomething);

thread begin //

Ui08 *pointerSomething;
Ui64 localVariable;

case 3: 

   pointerSomething=&addressOfSomething;
   memcpy( &localVariable, pointerSomething, sizeof(localVariable) );

break;

thread end //

If I change these line as you can see above, the problem is fixing for all time of case. But my question is why this problem is occuring, casting type of line?

1

There are 1 answers

0
0___________ On

There is nothing to guess here.

gcc is compiling for Cortex-M7 (thumb) 64-bit pointer pun to the LDRD instruction. LDRD instruction requires aligned addresses. That is the reason why you are getting hardFaults from time to time when the address is not word aligned.

https://godbolt.org/z/o9sPvfaon

You need to make sure that the pointer references correctly aligned data. During debugging you can for example:

case 3: 

   if((uint32_t)pointerSomething & 3)
   {
       __BKPT();
   }
   localVariable = *(Ui64*)(pointerSomething);

and you will be able to see what is causing the HF.