There's two possible issues:
- The cast may be subject to alignment restrictions.
- Reading or writing through the result of the cast is subject to the strict aliasing rule.
For part 1, it's implementation-defined whether a platform has alignment requirements. Consult the compiler documentation and it must say whether such restrictions exist. If they do, then it is undefined behaviour if the pointer you cast is not correctly aligned for the type pointed to by the target of the cast.
For part 2, you need to understand the strict aliasing rule. See this thread for a Standard quote plus various forms of introduction.
My answer from hereon in only refers to working in dynamically allocated space. A problem would occur if data was read and written via different types where the type doing the reading is not allowed to alias the type that did the writing:
uint16_t *buf = malloc(50);
((char *)buf)[0] = 'a';
((char *)buf)[1] = 'b';
*buf; // undefined behaviour
So to answer your question, you need to know how the data was written.
In the case of fread
, the standard (C11 7.21.8.1/2) specifies that it writes as if there were a series of assignments to unsigned char
characters. So it would be undefined behaviour to fread
into a malloc'd buffer and then read via a uint16_t
expression.
The mmap
function is not part of the C Standard. So the standard doesn't cover what would happen if you read out of mmap
'd space before writing into it. But I would say that if you write into such space and then read from the same address, then the strict aliasing rule would apply.
Some compilers have switches or pragmas to "disable strict aliasing" , meaning that they will compile the code as if all aliasing was permitted. If you want to use coding techniques that violate the strict aliasing rule then it would be a good idea to use such switches for that code.