3

Possible Duplicate:
C programming : How does free know how much to free?

In this snippet

void main() {
void *p = malloc(300);
printf("%d",sizeof(*p));
free(p);
}

How does free know much memory it is supposed release from the void pointer?

I figure, if there is an internal table/function, it should be available to find out sizes of any kind of objects, whereas the output of the printf is 1

Community
  • 1
  • 1
Rohan Monga
  • 1,759
  • 1
  • 19
  • 31

4 Answers4

3

see comp.lang.c FAQ list · Question 7.26

Josh
  • 335
  • 1
  • 9
3

malloc and free do their own hidden accounting so they can do the correct thing.

The reason the sizeof() does not use this accounting information is that sizeof() is a compile time operator, and the malloc/free information is not available until runtime.

Darron
  • 21,309
  • 5
  • 49
  • 53
1

This is implementation dependant. In some systems I've seen, it reserves some bytes before the pointer with information of the size of the reserved chunk, next free slot of memory, etc. As for the sizeof(void), this is not specified.

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
0

Each implementation of malloc has an internal data structure of how many blocks it allocated. free and malloc go hand-in-hand so free knows exactly where to look.

See this Wiki article on Free List for more information

SiegeX
  • 135,741
  • 24
  • 144
  • 154
  • "... of how many blocks it allocated", of the location of each block allocated, and of the size of each block allocated: so for any block that's being freed, it (the 'heap implementation') remembers how big that block was. – ChrisW Dec 01 '10 at 17:54
  • this article should really be on wiki's malloc & free articles – Rohan Monga Dec 01 '10 at 18:00