There is no technical issue stopping the C Standard committee from adding a new library function to retrieve the number of bytes accessible via a valid pointer previously returned by malloc()
, calloc()
, realloc()
, aligned_alloc()
, strdup()
or any similar function. The number returned would not necessarily be the size initially passed to the allocation function, and it is conceivable that this information might be not be available at all, so a return value of 0
would indicate that the information is not available.
The reason such a function has not yet been added might be that the C Standard committee is usually very reluctant at adding new functions. For example it took more than 30 years for strdup()
to finally make its way into the C Standard (it will be part of the next version) despite consistent implementations having been available in most C libraries for decades.
This function would have undefined behavior for any pointer not previously returned by a memory allocation function or already freed, just like free
or realloc
. Whether it is defined for NULL
is debatable, but a return value of 0
seems appropriate in this case. If the size is not known, which is possible for dummy allocators that do not store this information, a return value of 0
would indicate this condition too.
Here is an abstract from the man page for malloc_usable_size
present in the GNU lib C:
NAME
malloc_usable_size
- obtain size of block of memory allocated from heap
SYNOPSIS
#include <malloc.h>
size_t malloc_usable_size(void *ptr);
DESCRIPTION
The malloc_usable_size()
function returns the number of usable bytes in the block pointed to by ptr
, a pointer to a block of memory allocated by malloc(3)
or a related function.
RETURN VALUE
malloc_usable_size()
returns the number of usable bytes in the block of allocated memory pointed to by ptr
. If ptr
is NULL
, 0
is returned.
ATTRIBUTES
Multithreading (see pthreads(7)
): the malloc_usable_size()
function is thread-safe.
CONFORMING TO
This function is a GNU extension.
NOTES
The value returned by malloc_usable_size()
may be greater than the requested size of the allocation because of alignment and minimum size constraints. Although the excess bytes can be overwritten by the application without ill effects, this is not good programming practice: the number of excess bytes in an allocation depends on the underlying implementation.
The main use of this function is for debugging and introspection.
SEE ALSO
malloc(3)