I want to know the size of a buffer allocated using calloc
in byte
. By testing the following in my machine:
double *buf = (double *) calloc(5, sizeof(double));
printf("%zu \n", sizeof(buf));
The result was 8 even when I change to only one element I still get 8. My questions are:
sizeof
will return 40).char
, int
, double
, or float
)?Any ideas are appreciated.
Quoting C11
, chapter §6.5.3.4 , (emphasis mine)
The
sizeof
operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. [...]
So, using sizeof
you cannot get the size of the memory location pointed to by a pointer. You need to keep a track on that yourself.
To elaborate, your case is equivalent to sizeof (double *)
which basically gives you the size of a pointer (to double) as per your environment.
There is no generic or direct way to get the size of the allocated memory from a memory allocator function. You can however, use a sentinel value to mark the ending of the allocated buffer and using a loop, you can check the value, but this means
Choose according to your needs.