*((uint32_t*)foo))
In this expression, foo
is type-casted to a uint32_t
pointer and then dereferenced.
Dereferencing a cast of a variable from one type of pointer to a different type is usually in violation of the strict aliasing rule¹, and
*((uint32_t*)foo))
does exactly that. So the expression invokes undefined behaviour.
Furthermore, foo
might not be properly aligned:
From C11:
1 The behavior is undefined in the following circumstances:
....
Conversion between two pointer types produces a result that is
incorrectly aligned (6.3.2.3)
With 6.3.2.3p7 saying
[...] If the resulting pointer is not correctly aligned [68] for the
referenced type, the behavior is undefined. [...]
Unaligned data is data at an address (pointer value) that is not evenly divisible by its alignment (which is usually its size).
NB that empty initializer lists are not valid till C23, and just because int32_t
happens to be int
on your compiler/platform doesn't mean that it might not be long
on another.
%d
in not the correct format specifier for an int32_t
. If you don't want to use the specific macros for fixed-width integer types, another approach is to cast to intmax_t
/ uintmax_t
and use %jd
and %ju
respectively.
Footnote:
1
See: What is the strict aliasing rule?