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?
Asked
Active
Viewed 99 times
0

Iharob Al Asimi
- 52,653
- 6
- 59
- 97

Erik W
- 2,590
- 4
- 20
- 33
-
Are you asking should C de designed explicitly to create memory leaks? – juanchopanza Feb 21 '15 at 13:43
-
I just want to know how it works – Erik W Feb 21 '15 at 13:45
-
No, you should `free()` the whole block, in fact if you pass a pointer that was not returned by one of *`malloc()` function, it's undefined behavior. – Iharob Al Asimi Feb 21 '15 at 13:45
-
Please write why you downvote :) – Erik W Feb 21 '15 at 13:47
-
@ErikW But you're not asking how it works. – juanchopanza Feb 21 '15 at 13:48
-
1If you want to know exactly how it works, google `malloc.c` and look at the source of various implementations… – Arkku Feb 21 '15 at 13:52
2 Answers
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