How do malloc & free work in C?
Tags: c, cpp, computerscience, programming
Published: 2019-11-01 10:34:05

<!-- wp:paragraph -->
<p>As we know, the process can allocate &amp; deallocate memory using malloc &amp; free in C language. But do you ever consider what happens behind the scene ? or How do malloc &amp; free work? Let see </p>
<!-- /wp:paragraph -->

> /!\\\: Originally published @ [www.vishalchovatiya.com](http://www.vishalchovatiya.com).

<!-- wp:heading -->
<h2>Allocating Memory on the Heap</h2>
<!-- /wp:heading -->

<!-- wp:image {"id":1731,"align":"left"} -->
<div class="wp-block-image"><figure class="alignleft"><img src="http://www.vishalchovatiya.com/wp-content/uploads/program-break-malloc-free-in-c.png" alt="How do malloc &amp; free work in C" class="wp-image-1731"/></figure></div>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li>A process can allocate memory by increasing the size of the heap.</li><li>Heap is a variable-size segment of contiguous virtual memory that begins just after the uninitialized data segment of a process and grows &amp; shrinks as memory allocated and freed.</li><li>The current limit of the heap referred to as the program break which is just at the end of the uninitialized data segment in process address space.</li><li>Resizing the heap (i.e., allocating or de-allocating memory) is as simple as telling the kernel to adjust its idea of where the process’s program break is.</li><li>To allocate memory, <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://www.vishalchovatiya.com/how-c-program-converted-into-assembly/" target="_blank"><span style="color:#150aec" class="color">C programs</span></a> normally use the malloc family of functions, which we describe shortly. However, we begin with a description of <code>brk()</code> &amp; <code>sbrk()</code>, upon which the malloc functions are based.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Pre-requisites:</strong>&nbsp;<a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://www.vishalchovatiya.com/how-c-program-stored-in-ram-memory/" target="_blank"><span style="color:#1e0ce5" class="color">Memory layout of C program</span></a>&nbsp;OR&nbsp;<a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://www.kernel.org/doc/gorman/html/understand/understand007.html" target="_blank"><span style="color:#0e23e0" class="color">Understanding of process address space</span></a><span style="color:#0e23e0" class="color"> </span></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3><code>brk()</code> &amp; <code>sbrk()</code></h3>
<!-- /wp:heading -->

<!-- wp:enlighter/codeblock {"language":"c"} -->
<pre class="EnlighterJSRAW" data-enlighter-language="c" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#include &lt;unistd.h>

int brk(void end_data_segment);

void *sbrk(intptr_t increment);</pre>
<!-- /wp:enlighter/codeblock -->

<!-- wp:list -->
<ul><li>The <code>brk()</code> is a system call which sets the program break to the location specified by <code>end_data_segment</code>. Since virtual memory is located in units of pages, <code>end_data_segment</code> is effectively rounded up to the next page boundary.</li><li>A call to <code>sbrk()</code> adjusts the program break by adding an increment to it. On Linux, <code>sbrk()</code> is a library function implemented on top of <code>brk()</code>. On success, <code>sbrk()</code> returns the previous address of the program break. In other words, if we have increased the program break, then the return value is a pointer to the start of the newly allocated block of memory. The call <code>sbrk(0)</code> returns the current setting of the program break without changing it. This can be useful if we want to track the size of the heap, perhaps to monitor the behaviour of a memory allocation package.</li><li>After the program break increased, the program may access any address in the newly allocated area, but no physical memory pages allocated yet. The kernel automatically allocates new physical pages on the first attempt by the process to access addresses in those pages.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2 id="How-do-malloc-&amp;-free-work">How do malloc &amp; free work?</h2>
<!-- /wp:heading -->

<!-- wp:heading {"level":3} -->
<h3>malloc</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>When you malloc a block, it first checks how much memory you requested.</li><li>There are 2 ways to get memory from the system: 1. <code>mmap()</code>, 2. <code>brk()</code>.</li><li>When you request some byte to be <span data-preserver-spaces="true">allocated&nbsp;</span>by malloc it checks for <code>MMAP_THRESHOLD</code> limit(this also depends upon library implementations). If you request more than that limit, then <code>mmap()</code> system call used to obtain the requested memory.</li><li>Else it uses <code>brk()</code> syscall, increments the program break size &amp; gives you a pointer to start of newly allocate contiguous block.</li><li>Whichever procedure it follows, it allocates a bit more memory than you asked for. This extra memory(also known as meta-data) used to store information such as the size of the allocated block. And a link to the next free/used a block in a chain of blocks, and sometimes some guard data(that helps the system to detect if you write past the end of your allocated block).</li><li>Also, most allocators will round-up the total size and/or the start of your part of the memory to a multiple of bytes (e.g. on a 64-bit system may align the data to a multiple of 64 bits (8 bytes) as accessing data from non-aligned addresses can be more difficult and inefficient for the processor/bus), so you may also end up with some "padding" (unused bytes).</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>free</h3>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>As we know so far that we allocate the memory just by increasing the program's break.</li><li>And upon your intellect, you must be thinking that free will lower this program break.</li><li>But it's not, free simply adds the block of memory to list of free blocks that are recycled by future calls to <code>malloc()</code>. But why?</li><li>Well, the block of memory being freed is typically somewhere in the middle of the heap, rather than at the end, so that lowering the program break is not possible.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>Will malloc allocates contiguously in memory or it scattered?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Yes &amp; no both, Here is why!</li><li>In a typical OS, there exists the concepts of virtual memory and physical memory.</li><li>Each process has its virtual memory range which is contiguous.</li><li>When you allocate memory through malloc, the program break increased with respect to virtual memory. So your allocated byte is contiguous.</li><li>But the OS, behind the scenes, is busy mapping virtual memory allocations onto real blocks of physical memory which do not be contiguous because this is how VMM(Virtual Memory Manager) works. You can read more about it <a rel="noreferrer noopener" aria-label="here (opens in a new tab)" href="http://www.vishalchovatiya.com/how-does-virtual-memory-work/" target="_blank"><span style="color:#0f24e5" class="color">here</span></a>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2>How does free know how much to free?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>If you still can not figure out the answer to this question, you may read the <a href="#How-do-malloc-&amp;-free-work"><span style="color:#1b07f0" class="color">above topics</span></a> again. </li><li>Anyway. When you call <code>malloc()</code>, you specify the amount of memory to allocate. The amount of memory used is slightly more than this and includes extra information that records (at least) how big the block is.</li><li>You can't (reliably) access that other information - and nor should you.</li><li>When you call <code>free()</code>, it simply looks at the extra information to find out how big the block is. </li></ul>
<!-- /wp:list -->

## Other related articles

- [How floating-point no is stored in memory?](https://dev.to/visheshpatel/how-floating-point-no-is-stored-memory-47od)
- [How C program converts into assembly?](https://dev.to/visheshpatel/how-c-program-converts-into-assembly-3m2f)
- [How C program stored in RAM memory?](https://dev.to/visheshpatel/how-c-program-stored-in-ram-memory-3773)

[Have any suggestions, query or wants to say `Hi`? Take the Pressure Off, you are just a click away.](http://www.vishalchovatiya.com/contact-2/)🖱️