Determine the size of the buffer allocated to the heap

I want to know the size of the buffer allocated with callocin byte. Having tried the following on my machine:

double *buf = (double *) calloc(5, sizeof(double));
printf("%zu \n", sizeof(buf));

The result was 8, even when I switch to only one element, which I still get 8. My questions are:

  • Does this mean that I can only multiply 8 * 5 to get the size of the buffer in bytes? (I thought I would sizeofreturn 40).
  • How to make a macro that returns the buffer size in bytes (checked buffer may be char, int, doubleor float)?

Any ideas are welcome.

+4
source share
2 answers

Citation C11, chapter §6.5.3.4, (emphasis added)

sizeof ( ) , . . [...]

, sizeof, , . .

, sizeof (double *), ( ) .

. , , ,

  • .

.

+6

sizeof(buf) - buf, , , .

- ( ) , calloc(), , , , calloc() .
5 * sizeof(double).

Afaik , , ; ( malloc(), calloc(), realloc() .

+2

Source: https://habr.com/ru/post/1679023/


All Articles