I know about this: Do I cast the result of malloc?
I read it and other questions, and I still haven't satisfied my concerns. I understand that the type cast will occur implicitly, but the error is something I do not understand no matter how much I read these arguments.
The main argument is that int and pointer may have different sizes. For the sake of an example, let size of int* be 8 and size of int be 4.
int *x = (int*) malloc(sizeof(int));
First off, the number of bytes allocated by malloc() is 4, although the variable x will store a pointer of size 8 bytes.
I'm explicitly casting the return of malloc to (int *), which — by the way — has size 8. How come there's any loss of bits here?
If you haven't #included stdlib.h, the return value of malloc is most likely truncated before it gets returned to the calling code. In theory, it is undefined behavior. If the return value of malloc is truncated, it's analogous to using:
int a = 10;
int* ap = &a;
int temp = (int)ap; // This is where you lose the pointer value due to truncation.
int* bp = (int*)temp;
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