Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does glibc (GNU C Library) provide a way to obtain the size of an allocated memory block?

I have a pointer. I know its address (I got as an argument to a function), and I know that it points to a memory address previously allocated by the malloc() call.

Is there any way to know the size of this allocated memory block?

I would prefer a cross-platform, standard solution, but I think these do not exist. Thus, anything is okay, even hardcore low-level malloc data structure manipulation, if there is no better. I use glibc with x86_64 architecture and there is no plan to run the result elsewhere. I am not looking for a generic answer, it can be specific to glibc/x86_64.

I think, this information should be available, otherways realloc() could not work.


This question asks for a generic, standard-compliant solution, which is impossible. I am looking for a glibc/x86_64 solution which is possible, because the glibc is open source and the glibc realloc() needs this to work, and this question allows answers by digging in non-standard ways in the low-levels malloc internals.

like image 806
peterh Avatar asked Feb 11 '21 18:02

peterh


1 Answers

malloc_usable_size returns the number of usable bytes in the block of allocated memory pointed to by the pointer it is passed. This is not necessarily the original requested size; it is the provided size, which may be larger, at the convenience of the allocation software.

The GNU C Library apparently does not document this directly:

  • This part of the GNU C Library documentation says it provides malloc_usable_size but does not document its behavior, and it appears to be the only mention in the full documentation there.
  • This GNU C Library page says its API is documented by the Linux man-pages project, among others, and those pages point to this for malloc_usable_size.

So I suppose you may take that last page as having the imprimatur of the GNU C Library. It says size_t malloc_usable_size(void *ptr) “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,” and indicates the function is declared in <malloc.h>. Also, if ptr is null, zero is returned.

like image 172
Eric Postpischil Avatar answered Sep 18 '22 00:09

Eric Postpischil