Search code examples
cpointerssizeof

Determine the size of buffer allocated in heap


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:

  1. Does it mean that I can only multiply 8*5 to get the buffer size in byte? (I thought sizeof will return 40).
  2. How can make a macro that return the size of buffer in byte (the buffer to be checked could be char, int, double, or float)?

Any ideas are appreciated.


Solution

  • 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

    • the allocation of an extra element to hold the sentinel value itself
    • the sentinel value has to be excluded from the permissible values in the memory.

    Choose according to your needs.