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.
sizeof(buf)
is the size of the buf
variable, which is a pointer, not the size of the buffer it points to.
Due to memory alignment requirements (imposed by the hardware), the size of the block allocated with calloc()
is at least the product of the values you pass to calloc()
as arguments.
In your case, the size of the buffer is at least 5 * sizeof(double)
.
Afaik there is no way to find the size of a dynamically allocated block of memory but as long as you allocate it, you already know its size; you have to pass it as argument to the memory allocation function (be it malloc()
, calloc()
, realloc()
or any other.
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