We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hi
I am using MDK5.11a on STM32F050. I come across a hard fault, which I eventually find out it is the following construct that causes the problem.
The following is just to demonstrate the fault.
uint8_t array[30] ; uint32_t *intptr ; uint8_t i ; ..... ..... for(i = 0 ; i <= 10 ; i++) { intptr = *(uint32_t*)&array[i]) ;
// then access via the integer pointer if(*intptr == 0) {.... } }
sure, sooner or later, it crashes with hard fault.
My problem in using this approach to access 32 bit is that I received a stream of data from the USART, and put into the array. Depending on the header bytes, somewhere down the stream, the data bytes can either be interpreted as uint16_t or uint32_t, so accessing the 1st byte of the uint32_t by casting its address to uint32_t* and accessing it as 32 bit may bear the problem if the 4 bytes are not aligned correctly, which in my case, is very likely.
The easy way is copy byte by byte (memcpy) into a uint32_t variable and then further processing the variable. But is there any easy way (compiler directives)? As the construct is C compliant, I would have thought that it is the work of the compiler to deal with this automatically without user knowledge about this cross boundary problem?
Rgds
Calvin
This is a bad habit that you (and many others) just happened to get away with in the 8-bit world!
"May be you guys are interested to explain why this is the case"
As already noted, the language specification states that the behaviour is undefined - so there doesn't have to be any rhyme nor reason to it. There isn't really any benefit to analysing it - just don't do it!
It is certainly not something that you should rely upon!
"This is a bad habit that you (and many others) just happened to get away with in the 8-bit world!"
The first time I did program on Sun workstations I couldn't understand why my program failed with "Bus error" when the code could be compiled and run without any problems on a PC. Not all programs that can be compiled and run are actually correct with regards to the C language standard. It's really bad to rely on undefined behavior.
And a program which can be compiled and run and is "correct" with regards to the C language standard may not do what the programmer wanted.
The classic example being:
if( x = 1 ) ... ;
When what the programmer wanted was
if( x == 1 ) ... ;