Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type casting in malloc [duplicate]

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?

like image 816
Judismar Arpini Junior Avatar asked Apr 20 '26 11:04

Judismar Arpini Junior


1 Answers

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;
like image 96
R Sahu Avatar answered Apr 23 '26 01:04

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!