What ((size_t*)ptr)[-1] mean in C?

  • A+

I want to know the size allocated to a pointer.

So I found this answer : how can i know the allocated memory size of pointer variable in c

And it has the below code.

#include <stdlib.h> #include <stdio.h>  void * my_malloc(size_t s)  {   size_t * ret = malloc(sizeof(size_t) + s);   *ret = s;   return &ret[1]; }  void my_free(void * ptr)  {   free( (size_t*)ptr - 1); }  size_t allocated_size(void * ptr)  {   return ((size_t*)ptr)[-1]; }  int main(int argc, const char ** argv)  {   int * array = my_malloc(sizeof(int) * 3);   printf("%u/n", allocated_size(array));   my_free(array);   return 0; } 

The line (((size_t*)ptr)[-1]) works perfectly, but I don't understand why...

Can someone help me understand this magic line? Thanks!


Seems that your compiler's C malloc implementation keeps the allocated size (in bytes) in the 4 bytes right before the address it returns.

By converting the returned address (ptr) to a pointer-to-size_t (that's ((size_t*)ptr)), and then taking the aligned address right before it (that's the '[-1]', which is actually just pointer arithmetic - same as writing *(((size_t*)ptr) - 1)) - you can access the allocated size (of type size_t).

This is to explain what ((size_t*)ptr)[-1] means and why it seems to work, but this is by no means a recommendation on using it. Getting the size allocated to a pointer was a quantity asked by the application-code and should be managed by it if needed, while not relying on compiler implementations.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: