Hardware error due to memory byte alignment

When debugging STM32 programs recently, I often enter the HardFault_Handler interrupt. The reason for this interrupt is generally related to memory, such as array out of bounds, stack overflow and the like.

After checking for several days, I finally found the problem. The reason for the problem is that when the program is running the function pointed to by the pointer, the HardFault_Handler interrupt is caused by the wrong address pointed to by the pointer.

This is where I can't believe that there are some invalid assignments to this pointer in my program, so I started to debug the code that assigns this pointer, and found an unexpected thing . There is no problem with the assignment code, but after completing the assignment operation, the address pointed to by the function pointer is not the same as the address I assigned to it. There was a scene of galloping horses in my heart.

But why does this happen? Well, in the end I didn't figure out why. However, I don't know if the solution is a coincidence or what. When I was looking for HardFault_Handler related information on the Internet, I found that someone mentioned memory byte alignment. So I figured out that there are some data structures in my program that I set to 1-byte memory alignment. It is #pragma pack (1)implemented using , but I did not add to #pragma pack ()cancel the custom memory alignment instruction, so that the data structures after it are all 1-byte aligned. After I added it , the #pragma pack ()program did not enter the HardFault_Handler interrupt.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325582122&siteId=291194637