sizeof(d)
gives the size of the pointer, d
. A value of 8
is consistent with a 64-bit host system.
This is distinct from the allocated size of whatever d
points at.
Since malloc()
allocates at run time (the length to be allocated is specified when the program is run) and sizeof
is a compile-time operator, it is not possible to use sizeof
to obtain the length.
You need to track the size manually, in a separate variable.
size_t allocated_size = 5*sizeof int;
int *d = malloc(allocated_size);
printf("%d", (int) allocated_size);
It is more common to track the number of elements (i.e. take account of the type of d
).
size_t allocated_ints = 5;
int *d = malloc(allocated_ints * sizeof (*d));
printf("%d", (int) allocated_ints); // prints number of `int`
size_t
is defined in <stdlib.h>
(among others). In C99 and later, the format specifier for printing a size_t
is %zu
(rather than converting to int
and using %d
as you have done).