I came across this piece of code:
void incme(double *p)
{
*p += 1;
}
int i = 1;
incme((double *)&i); /* WRONG */
When I try to execute it, I get core dump. What is wrong with this code. Can we not type cast an int pointer to a double type.
Thank you.
You're not casting an int to a double, you're casting an int * to a double *. That's not safe if sizeof(double) and sizeof(int) aren't the same...
Even if you match up the storage sizes, what do you expect the output to be? Floating-point types and integers tend not to have any kind of compatible representations.
(int) is usually aligned to 4 bytes on 32-bit hardware, while (double) usually needs to be 8-byte aligned. If your i isn't on an 8-byte aligned address, you can expect SIGBUS; also, if it's allocated on the stack, the larger (double) is likely to overwrite the call frame leading to a core dump when incme() returns, if the preceding doesn't kill it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With