When executing this C code:
double *t = (double*) malloc(10 * sizeof(double));
printf("%lun", sizeof(t)/sizeof(t[0]);
for (int j = 0; j < 10; j++) {
t[j] = 5 * powl((j/10), 0.4);
printf("t_j: %lfn", t[j]);
}
My array has only 0
stored and the size of my array is 1
.
I am using Xcode. With thread sanitiser turned on I get an error that malloc
can’t allocate memory in vm-space.
malloc: nano zone abandoned due to inability to preallocate reserved vm space.
3
Answers
sizeof
on a pointer returns the size of the pointer, not the pointed to data.The
sizeof
trick would only work with an array.Note that
sizeof
returnssize_t
, not anunsigned long
. The correct format specifier is%zu
.There’s no way to get the number of elements a pointer is pointing to. You have keep track of the size yourself.
Another approach would be to define it as an array:
And now the
sizeof
idiom would work.The cast is not required. It only serves to clutter one’s code.
malloc(3)
returnsNULL
to indicate failure, leaving it unchecked risks invoking undefined behaviour.sizeof
is giving you the size of the object. In your casesizeof(t)
is giving the size of the pointereTo see the size of the array you need to define it as an array
The variable
t
is declared as a pointer of the typedouble *
.So the expression
sizeof(t)/sizeof(t[0])
is equivalent tosizeof( double * ) / sizeof( double )
and does not yield the number of elements in the allocated array.Also in this statement
there is a typo. You need to add one more closing parenthesis.
And though the type
size_t
usually is defined as an alias for the typeunsigned long
it is more correctly to use the conversion specifier%zu
instead of%lu
because the C Standard allows in some implementations to define it as an alias for the typeunsigned long long
.Also in this expression
(j/10)
there is used the integer arithmetic. So it always evaluates to 0. You should write(j/ 10.0)
to convert operands of the expression to the common typedouble
.