0

I know that depending of the implementation of malloc, the algorithm used differs (free linked lists, buckets, binary buddy... - and often it is a mix).

So I was wondering if it is possible to know the size of the metadata stored by malloc for a certain block and access it even as a copy.

I have not found any standard function or method to do it.

Any idea?

7
  • 4
    There is no standard function for this. You need to look at the individual implementation of the C library you're using. Just curious: what do you want to do with that meta data or its size? Commented Nov 6, 2024 at 12:43
  • 1
    This is a very typical XY problem. Why do you need this information? What actual problem is it supposed to solve? Commented Nov 6, 2024 at 12:45
  • 1
    As you already wrote: "Depending on the implementation..." How would any standard function provide access to data that is not defined by the standard? Commented Nov 6, 2024 at 12:45
  • Usually it is accessible through wild & crazy pointer arithmetic as an offset of the address you received from malloc. But you need to know what implementation that is used in order to write a hack to inspect those bytes. Commented Nov 6, 2024 at 12:53
  • I don't "need" this information, it's purly informative. I am coding my own malloc and I was just wondering how much memory is used by a standard implementation of malloc (I mean, one which is well coded:) for each block. Like, if I malloc(1), how much bytes are really used in memory? Commented Nov 6, 2024 at 13:03

1 Answer 1

4

There is no standard function to get the metadata for a malloc block, because as you correctly note, the location and contents of the metadata block are heavily implementation-dependent.

There are implementation-specific functions that you can use to get some information about heap blocks, for example, malloc_usable_size(void *ptr) in GNU libc. Other malloc implementation may support similar extensions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.