I have read this question: How does casting uint8* to uint32* work? but I am unsure of the answer given.
I'm newbie embedded C programmer working on an project that uses GCC and I've been refactoring chunks of code to reduce the memory usage. An example is where I changed the data types of some variables from uint32_t
to smaller sized types:
uint8_t colour;
uint16_t count;
uint16_t pixel;
func((uint32_t*)&colour);
func((uint32_t*)&count);
func((uint32_t*)&pixel);
Where func(uint32_t* ptr)
modifies the value passed in to data it receives on a slave port. I'm coming across a problem where the above code does not behave correctly when -O1
, -O2
, -O3
or -Os
optimisation is enabled. E.g when values 1
5
1
are received on the comms port and the function respectively, the value that is set for the variables are 0
0
1
. When no optimisation is enabled, the values are set correctly.
The code behaves correctly if I change the data types back to uint32_t
. I don't understand why I don't get any warnings from the compiler (I have extra warnings turned on). Is the reason this is happening to do with the endianess/allignment?
What are the pitfalls of upcasting from a uint8_t
pointer to a uint32_t
pointer?