Memory allocation (source code)

= Memory allocation

<Memory allocation> reserves <computer memory> for a program’s data and makes that storage accessible through <memory addresses>. Allocation determines where data can live and how long the storage remains available; initialization determines the data’s initial value. A language can arrange storage automatically for local variables, retain storage for the duration of a program, or request storage dynamically while the program runs.

In the <C programming language>, `malloc(n)` requests a block of $n$ <bytes> and returns a <pointer> to it, or a null <pointer> if allocation fails. Successful allocation does not initialize those <bytes>. The `free` operation releases a previously allocated block for subsequent allocation; accessing it through an old <pointer> is no longer valid.<The GNU C Library Reference Manual>[Version 2.24, section 3.2.2.1, Basic Memory Allocation]{ref}<C11 committee draft N1570>[Sections 7.22.3.3–7.22.3.4, printed pp. 348–349: free and malloc]{ref} Allocation and deallocation are therefore separate from reading and writing an object. Deallocation need not erase its former contents or immediately return its storage to the <operating system>.

For a process using <virtual memory>, a contiguous interval of <memory addresses> does not require a contiguous interval of physical memory. The <memory management unit> can map successive virtual pages to different physical <page frames>. Conversely, a successful small allocation may be satisfied from an existing free block without asking the <operating system> for another page.

Two small bookkeeping examples explain why free capacity alone does not determine whether an allocation succeeds. If an allocator rounds a 17-<byte> request up to a 32-<byte> allocation unit, 15 <bytes> are unused inside that unit: <internal fragmentation>, before counting any allocator metadata. If two free 32-<byte> blocks are separated by an occupied block, a request for one contiguous 48-<byte> block cannot fit in either hole, even though 64 <bytes> are free. That is <external memory fragmentation>, under the assumption that the occupied block cannot be moved and no further storage is available. Adjacent free blocks can sometimes be combined; separated ones require a different placement or movement strategy.