suraj_fale
suraj_fale

Reputation: 960

Logic behind Malloc Function

First of all sorry for my sloppy diagram below.

I want to understand logic behind malloc(). This was asked to me in Bloomberg interview.

Que:Consider only 2 bytes of memory left in your OS (as shown below).Now if I malloc() it for 2 bytes. (White region indicates free space in byte,and black indicates used space in byte. So we have 2-bytes free and 2-bytes used memory space).
Memory Region

P.S:- I checked on google and I found it is dependent on OS mostly. But I would like to have more insight on it.

Thank you!

Upvotes: 0

Views: 332

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

There are a number of issues here (note that most of what's below is specific to Linux, but I guess will be similar on other platforms):

  • A typical implementation of malloc will never allocate only 2 bytes (due to efficiency and alignment concerns). For example, the standard GNU implementation allocates a minimum of 16 bytes by default, I think.

  • malloc operates in user-space, on memory regions already provided by the OS. The OS only gets involved once malloc exhausts what it has available and needs to request a bigger memory region for the heap.

  • The OS must allocate memory regions to processes in units of pages (typically 4kB), as this is the fundamental unit of the hardware memory-management unit (MMU). Therefore, it doesn't make sense to talk about the OS only having 2 bytes left.

  • The OS usually allocates memory regions that don't currently map to any physical memory (this is known as overcommitting). A physical mapping is only created when the process tries to access the memory.

  • If the OS gets low on physical memory, it uses a system known as page-frame reclaiming to steal page frames from other processes.

So in short, the scenario described in your question is unlikely to occur, for several reasons!

Upvotes: 1

Related Questions