开发者

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

I came across this piece of code:

void incme(double *p)
{
    *p += 1;
}

int i = 1;
incme((double *)&开发者_Python百科;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.


You can cast any pointer from one type to any other type, but that does not make it correct. In this case if sizeof(double) != sizeof(int) then line in "incme" will most probably write to memory outside of that allocated to the "i" integer. All bets are off then.


There's a difference between type conversion and memory reinterpretation.

Your code forcefully converts a pointer of int * type to double * type. That is achieved by using an explicit cast. This action alone does not necessarily lead to any problems by itself. So, the assumption that you made in the title of your question is incorrect. The "core dump" you observe has nothing to do with the cast itself.

Once you performed the conversion you proceed to dereference the resultant pointer and access (modify) the memory it points to. That's when the real problem takes place. The code performs data reinterpretation: it attempts to access an object of type int as an object of type double. This is always explicitly illegal in C language. The crash you observe is caused specifically by this reinterpretation attempt.

So, the short answer to your question is: You can certainly cast a pointer that points to an int object to double * type. But you cannot dereference the resultant double * pointer and access the memory as if it holds a double object.


On most platforms, double is 8 bytes, and int 4, therefore no you can not cast int* to double* and use it


One way to do it is:

int i = 1;
double d1 = (double)i;
double *d = &d1;
incme(d);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜