0

If you use malloc() to allocate memory for 4 integers, should it not return the memory adress of the first integer? And if so, shouldn't free() only free the first integer from the memory, while all the others are left behind?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Erik W
  • 2,590
  • 4
  • 20
  • 33

2 Answers2

3

shouldn't free() only free the first integer from the memory, while all the others are left behind

No, it shouldn't, because otherwise calling free would result in a memory leak most of the time.

To answer the question I think you might have wanted to ask, free has to de-allocate the whole memory block pointed at by its argument. How it does that is implementation specific, but there has to be some book-keeping going on behind the scenes in order to achieve this.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
3

malloc() keeps track of allocations made, including their size, and free() must be given exactly the address returned by malloc(), which causes that entire allocation to be freed at once.

Arkku
  • 41,011
  • 10
  • 62
  • 84
  • On a related note, if you consider the alternative, `malloc()` would have to keep track of every individual byte since `malloc()` does not know the type of data you intend to put in there (e.g., `malloc(8)` could be eight bytes, two 32-bit integers, or one 64-bit integer). – Arkku Feb 21 '15 at 13:50