If free() knows the length of my array, why can't I ask for it in my own code? If free() knows the length of my array, why can't I ask for it in my own code? c c

If free() knows the length of my array, why can't I ask for it in my own code?


Besides Klatchko's correct point that the standard does not provide for it, real malloc/free implementations often allocate more space then you ask for. E.g. if you ask for 12 bytes it may provide 16 (see A Memory Allocator, which notes that 16 is a common size). So it doesn't need to know you asked for 12 bytes, just that it gave you a 16-byte chunk.


You can't get it because the C committee did not require that in the standard.

If you are willing to write some non-portable code, you may have luck with:

*((size_t *)ptr - 1)

or maybe:

*((size_t *)ptr - 2)

But whether that works will depend on exactly where the implementation of malloc you are using stores that data.


After reading Klatchko's answer, I myself tried it and ptr[-1] indeed stores the actual memory (usually more than the memory we asked for probably to save against segmentation fault).

{  char *a = malloc(1);  printf("%u\n", ((size_t *)a)[-1]);   //prints 17  free(a);  exit(0);}

Trying with different sizes, GCC allocates the memory as follows:

Initially memory allocated is 17 bytes.
The allocated memory is atleast 5 bytes more than requested size, if more is requested, it allocates 8 bytes more.

  • If size is [0,12], memory allocated is 17.
  • If size is [13], memory allocated is 25.
  • If size is [20], memory allocated is 25.
  • If size is [21], memory allocated is 33.