In Linux or typically an OS with MMU for virtual memory management system like x86 architecture, I am realizing a scenario through an example where memory is available yet malloc can fail. Please confirm if this is actually possible.
Consider we have 4GB memory free in the system and we allocate 1 million of chunks of two sizes one after another, first is 3k and next is 1k which means we allocate 4k of one total chunk though there are two chunks and 1 million of this 4k total chunk, so we allocate total of 4GB of memory with each 1mb size. Allocation is in sequence with 3k chunk allocated for which OS MMU will allocate 1 page of 4k and it will then allocate rest of 1k of page for next 1k chunk.
Next consider that the process which is doing memory allocation will deallocate or free 1 million of 1k chunks so we should get 1GB of free memory. However, these chunks are sequential in address alternately allocated with 3k chunks, so we cannot reclaim this memory for further allocation unless next process alloc request is 1k or less. If the process in the future never request alloc of chunk equal or less than 1k or if it requests only for example 3k chunks in the future then this memory of 1GB freed by freeing 1k chunks will never be used.
How does MMU of OS like Linux will handle this? If this case is real that memory will go unused and there will be no further memory alloc possible, then in general this can have more scenarios like this. If Linux or any OS MMU handle this scenario and does not get memory wasted, how does it do that?
I know page allocation and how buddy allocators on Linux work though I could not find any solution to this issue with that else please explain if that can solve this. Apparently when 3k chunks are in use, we cannot break those virtual to physical memory mapping while process continues.