Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core dump on Pointer type-casting (int to double) in C

Tags:

c

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.

like image 434
jailed Avatar asked May 08 '26 21:05

jailed


2 Answers

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.

like image 193
Carl Norum Avatar answered May 11 '26 12:05

Carl Norum


(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.

like image 41
geekosaur Avatar answered May 11 '26 12:05

geekosaur