Pointer type-punning dangers
What you'll learn: Why forcing a pointer to treat memory as a different data type can lead to "Strict Aliasing" violations and unpredictable program crashes.
The "Wrong Glasses" Problem
Imagine you have a box containing a float (a number with a decimal). In C, you might be tempted to create an int pointer and point it at that same box. This is called "type-punning"—forcing the computer to look at the same bits through a different set of "glasses."
While it seems clever, this is dangerous. A float and an int might both be 4 bytes, but they use completely different binary patterns to represent values. If you change the "int" version, you might unintentionally turn your "float" into a nonsensical value or a "NaN" (Not a Number).
The Strict Aliasing Rule
Modern C compilers use a rule called Strict Aliasing. This rule assumes that pointers of different types (like int* and float*) will never point to the same memory location.
Because the compiler assumes they are separate, it might optimize your code by reordering instructions. For example, it might decide to read the value of your float before you finished updating it via the int pointer, thinking the two actions are unrelated. This leads to "undefined behavior"—the ultimate nightmare where your code works on Tuesday but crashes on Friday.
A Dangerous Example
Here is how type-punning looks in code. This often fails because the compiler doesn't expect ptr_as_int to affect my_float.
#include <stdio.h>
int main() {
float my_float = 10.5f;
// DANGER: Casting a float pointer to an int pointer
// This violates strict aliasing rules.
unsigned int *ptr_as_int = (unsigned int *)&my_float;
printf("Float value: %f\n", my_float);
// Modifying the bits as if they were an integer
*ptr_as_int = 0x3F800000;
// The result is unpredictable!
printf("New float value: %f\n", my_float);
return 0;
}
How to stay safe
If you truly need to look at the raw bits of a variable (for example, to send them over a network), the only safe way is to use a pointer to a character type (char* or unsigned char*) or the memcpy function. C makes a special exception for character pointers, allowing them to alias any type without breaking the rules.
Key takeaway
Never cast pointers between incompatible types; use char* or memcpy if you need to inspect raw memory.