Several dangers using reinterpret_cast<>
Reinterpreting smaller data pointer to bigger data pointers
Reinterpreting pointers of smaller data like char
to a pointer of bigger data like int
will cause issues like reading from unreserved memory, reading garbage values and other “bad” stuff.
For example:
char ch = 'A';
char* c_ptr = &ch;
int* i_ptr = reinterpret_cast<int*>(&ch); //this is "BAD" ❌
std::cout << *i_ptr << std::endl;
//ch is 1 byte but trying to access it using a int* will read 4 bytes and even though the whole thing will contain our char it will still have garbage values.
//int is 4 bytes so,
//byte1(our character) ~ byte2(??) ~ byte3(??) ~ byte4(??)
// read^(*i_ptr)
Does the garbage value contain our character ?
YES ! It will !
When converted to hex we will can see our character there as hex code, in this case 0x41
and if the whole thing is in negative we do a 2s complement
and it will contain our character in the LSB(follows little endian).
Why do a 2’s Complement ?
To understand this see -> Negatives and Complements
Using a different lvalue
and a different template arg
type
What if we do this ?:
int x = 64;
int *i_ptr = &x;
char* c_ptr = reinterpret_cast<float*>(&x); //compile error !
The lvalue
i.e. the char
pointer and the template arg
i.e. the float*
is different. It will simply result in a compile time error as it is a wrong syntax ! Both the pointer types should be same !