Is there a way in C to find out the size of dynamically allocated memory?
For example, after
char* p = malloc (100);
Is there
I would expect this to be implementation dependent.
If you got the header data structure, you could cast it back on the pointer and get the size.
Note: using _msize
only works for memory allocated with calloc
, malloc
, etc. As stated on the Microsoft Documentation
The _msize function returns the size, in bytes, of the memory block allocated by a call to
calloc
,malloc
, orrealloc
.
And will throw an exception otherwise.
https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/msize?view=vs-2019
There is no standard way to find this information. However, some implementations provide functions like msize
to do this. For example:
Keep in mind though, that malloc will allocate a minimum of the size requested, so you should check if msize variant for your implementation actually returns the size of the object or the memory actually allocated on the heap.