Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine the size of buffer allocated in heap

Tags:

c

pointers

sizeof

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.

like image 962
Don Avatar asked Feb 05 '23 07:02

Don


2 Answers

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.

like image 107
Sourav Ghosh Avatar answered Feb 16 '23 02:02

Sourav Ghosh


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.

like image 37
axiac Avatar answered Feb 16 '23 04:02

axiac