0

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?

mryldz
  • 95
  • 2
  • 9
  • 2
    You're probably violating alignment requirements. memcpy is the right tool. – Mat Aug 31 '22 at 12:52
  • 1
    Note that the size of a pointer is the size of the pointer itself, not what it might point to. So you probably want `sizeof localVariable` instead. And make sure that whatever `pointerSomething` is pointing to is at least eight bytes. – Some programmer dude Aug 31 '22 at 12:53
  • 2
    In addition to invalid alignment, it is very likely that this is also *strict aliasing violation* if type of `addressOfSomething` is not `Ui64`. Never use pointer dereference for type punning unless you know exactly what you are doing. Use `memcpy` instead. – user694733 Aug 31 '22 at 13:15

1 Answers1

0

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.

0___________
  • 60,014
  • 4
  • 34
  • 74