I was asked question in an quiz that a malloc() library call will always invoke mmap() or brk(). The answer is False. I am not able to get how it is possible?
Asked
Active
Viewed 73 times
-2
-
Suppose you call `malloc(1024)`. `malloc` calls `mmap` or `brk` to get the memory it needs for this. Later, you call `free` with that memory, and the memory allocation routines update their database to show the memory is available again. Then you call `malloc(1024)` again. This time, the memory allocation routines already have the memory, so they do not need to call `mmap` or `sbrk`; they just give you the memory that is already available. – Eric Postpischil Sep 13 '21 at 11:02
-
As a trivial counterexample, imagine a `malloc` implementation that calls e.g. `mmap` for a giant piece of memory the first time it's called, hands out parts of that, and later on just uses the rest of that piece. – gspr Sep 13 '21 at 11:03
-
Is your question not answered in the answer you linked? – sepp2k Sep 13 '21 at 11:11
-
Is your question, why `malloc` is not always implemented using `mmap` or `brk`? – Gerhardh Sep 13 '21 at 11:16
-
@sepp2k No, linked answer explained the internal working of malloc(), so from it I concluded mmap() or brk() are always invoked but Eric Postpischil cleared the confusion – jack rock Sep 13 '21 at 11:16
-
@jackrock I think you may have misread at least parts of the linked answer then. The answer lists finding free memory as step 1 and makes step 2 (`sbrk`/`mmap`) conditional on step 1 not succeeding ("Failing that..."). – sepp2k Sep 13 '21 at 11:29
-
Also, the linked answer talks about *a possible* malloc implementation, not *every possible* one. – gspr Sep 13 '21 at 12:15
1 Answers
0
The first time you call malloc(1)
it will ask the kernel for a whole bunch of memory, because the kernel has a minimum amount of memory it can give you. Then it will give you one byte of memory. The next time you call malloc(1)
it will give you another byte out of that big block it allocated. And so on until that block is used up. Then it will allocate more memory from the kernel.

user253751
- 57,427
- 7
- 48
- 90