14

How can one tell, given a void * pointer, what is the size of a block allocated on this given address (previously allocated using malloc; in Linux and Windows)? I hope both systems surely store this kind of information somewhere. That is, alternative of malloc_size which exists on OSX/Darwin. Using gcc/mingw if it helps.

Cartesius00
  • 23,584
  • 43
  • 124
  • 195
  • I think the size is stored along with other stuffs in some sort of struct just right before the pointer given to you by malloc. If not, it may be a pointer to such struct, since `free()` will need such data. – nhahtdh Jun 09 '12 at 08:36
  • @nhahtdh Yes, I also hope so, but I need it precisely. – Cartesius00 Jun 09 '12 at 08:36
  • @James, what will you do if I launch your application with my custom allocator on Linux? Like `LD_PRELOAD=my_super_allocator.so ./your_app`? I mean if you will think that there is a predifined structure behind `void*`. –  Jun 09 '12 at 08:53
  • possible duplicate of [How to find the sizeof(a pointer pointing to an array)](http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array) – Jens Gustedt Jun 09 '12 at 09:00
  • @JensGustedt: This question is about a malloc'ed buffer, not an array with known size at compile time... – Anders Jun 09 '12 at 09:20
  • @Anders, the answer is the same. A pointer has no more information than the address it is pointing to. – Jens Gustedt Jun 09 '12 at 12:11
  • 2
    @JensGustedt: It is not a random pointer, while the pointer itself clearly only stores the address, the "creator" knows extra information about this particular pointer. You would not pass any random pointer to free() would you? We are only talking about malloc and friends here, not a general pointer information function... – Anders Jun 09 '12 at 13:38

1 Answers1

14

On Windows, things that use the MS CRT can use _msize, on Linux you could try malloc_usable_size...

Tom Lee
  • 360
  • 1
  • 3
  • 10
Anders
  • 97,548
  • 12
  • 110
  • 164