0

How is it possible to get the size of memory allocated knowing only the pointer name returned by malloc function ? I suppose it is possible because free function as only this pointer as parameter but I do not know how to do that.

size_t myfoo (void *ptr) {
/* some instruction to get the size : This is the question*/ }

main () {
int * ptr;
ptr=malloc(100);
printf("%ud \n",myfoo(ptr)); }
Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • 1
    Yes, free obviously can or does. It's an implementation detail of the C standard library however. I suspect however that your question is a bit of a [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – StoryTeller - Unslander Monica Jan 08 '19 at 09:48
  • There is no standard function defined to know this. The malloc library has an internal data structure which may/probably knows the size of each allocated chunk of memroy, but there is no standard defined for the user. It is implementation dependent. – Paul Ogilvie Jan 08 '19 at 09:49
  • This related question may be of interest to you: https://stackoverflow.com/questions/1119134/how-do-malloc-and-free-work – AKstat Jan 08 '19 at 09:50
  • @StoryTeller. Yes, it is a XY problem related to this question https://stackoverflow.com/questions/54082905/structure-wrapper-and-variable-array-size – Stef1611 Jan 08 '19 at 10:18
  • And even `free()` might not know the *exact* size passed to `malloc()`, it might store the size rounded up to some arbitrary block size. – user4815162342 Jan 08 '19 at 10:25

0 Answers0