There is no general (standardized) way to do this, since the malloc implementation is a specific system and architecture. The only guaranteed behavior is that malloc(N) will return at least N bytes or NULL. malloc always allocates more memory than specified - to store the required size (N) and, as a rule, some additional accounting data.
Windows / Visual C ++ Specification:
Additional data is stored in the memory segment until the address malloc returns to.
If p = malloc(N) and p != 0 , you can use the following code to determine the size of the requested memory, if you only know p :
Windows NT: unsigned long ulAllocSize = *((unsigned long*)p - 4);
Windows CE: unsigned long ulAllocSize = *((unsigned long*)p - 2);
Note that ulAllocSize not the size of the entire block allocated with malloc , but only the value passed as its argument is N
source share