{"id":246,"date":"2024-09-24T11:59:00","date_gmt":"2024-09-24T14:59:00","guid":{"rendered":"https:\/\/suspensao.blog.br\/disbelief\/?p=246"},"modified":"2024-10-01T01:17:16","modified_gmt":"2024-10-01T04:17:16","slug":"implementing-malloc-and-free-old-memory-reused-first","status":"publish","type":"post","link":"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/","title":{"rendered":"Implementing malloc() and free() \u2014 old memory reused first"},"content":{"rendered":"\n<p>In the <a href=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-e-free-reducing-the-heap-even-more\/\">previous <em>post<\/em><\/a> in this series on implementing <code>malloc()<\/code>and <code>free()<\/code>, we showed how it is possible to reuse memory blocks and reduce the heap by freeing newer blocks. However, the current function introduces a subtle issue: it prioritizes reusing newer blocks, which can lead to increased memory consumption over time. Why does this happen? Let\u2019s break it down.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Heap reduction by reusing recent blocks<\/h3>\n\n\n\n<p>Consider the following scenario. First, we allocate four memory blocks:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void *ptr1 = abmalloc(8); <br>void *ptr2 = abmalloc(8); <br>void *ptr3 = abmalloc(8); <br>void *ptr4 = abmalloc(8);<\/code><\/pre>\n\n\n\n<p>The memory structure can be visualized like this:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"639\" height=\"45\" data-attachment-id=\"251\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/initial-list-2\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list.png?fit=639%2C45&amp;ssl=1\" data-orig-size=\"639,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"initial-list\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list.png?fit=639%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list.png?resize=639%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. Newer nodes point to older ones. All nodes are in use, so they are all labeled In use.\" class=\"wp-image-251\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list.png?w=639&amp;ssl=1 639w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>Now, we release the first and third blocks\u2026<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>abfree(ptr1); <br>abfree(ptr3);<\/code><\/pre>\n\n\n\n<p>\u2026resulting in the following structure:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"639\" height=\"45\" data-attachment-id=\"253\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/two-freed-list-1\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-1.png?fit=639%2C45&amp;ssl=1\" data-orig-size=\"639,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"two-freed-list-1\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-1.png?fit=639%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-1.png?resize=639%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. The newest nodes point to the oldest ones. The second and fourth nodes in the list (i.e. the second newest and oldest of all) have been freed with free(), so they are labeled with the word Available.\" class=\"wp-image-253\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-1.png?w=639&amp;ssl=1 639w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-1.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>Then we allocate another block of the same size:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void *ptr5 = abmalloc(8);<\/code><\/pre>\n\n\n\n<p>As the function <code>abmalloc()<\/code> starts searching for the most recent free block, it reuses the block at the top. If we now free the last block:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"639\" height=\"45\" data-attachment-id=\"255\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/one-reused-list-1\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-1.png?fit=639%2C45&amp;ssl=1\" data-orig-size=\"639,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"one-reused-list-1\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-1.png?fit=639%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-1.png?resize=639%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. Newer nodes point to older ones. Now only the last node is free and labeled with the word Free\" class=\"wp-image-255\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-1.png?w=639&amp;ssl=1 639w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-1.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>If we now release the last block\u2026<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>abfree(ptr4);<\/code><\/pre>\n\n\n\n<p>\u2026we can reduce the heap size by just one 8-byte block, since the previous block is no longer free:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"474\" height=\"45\" data-attachment-id=\"256\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/old-not-used-list\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/old-not-used-list.png?fit=474%2C45&amp;ssl=1\" data-orig-size=\"474,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"old-not-used-list\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/old-not-used-list.png?fit=474%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/old-not-used-list.png?resize=474%2C45&#038;ssl=1\" alt=\"Linked list with three nodes. Newer nodes point to older ones. The last node is free and labeled with the word Free.\" class=\"wp-image-256\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/old-not-used-list.png?w=474&amp;ssl=1 474w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/old-not-used-list.png?resize=300%2C28&amp;ssl=1 300w\" sizes=\"auto, (max-width: 474px) 85vw, 474px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Reuse of old blocks<\/h3>\n\n\n\n<p>Now, imagine the same scenario, but with one modification: our function starts searching for free blocks from the oldest one. The initial structure will be the same\u2026<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"647\" height=\"45\" data-attachment-id=\"257\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/initial-list-from-oldest\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list-from-oldest.png?fit=647%2C45&amp;ssl=1\" data-orig-size=\"647,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"initial-list-from-oldest\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list-from-oldest.png?fit=647%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list-from-oldest.png?resize=647%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. Older nodes point to newer ones. All nodes are in use and labeled with the word In use.\" class=\"wp-image-257\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list-from-oldest.png?w=647&amp;ssl=1 647w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/initial-list-from-oldest.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>\u2026and again we free the first and third memory blocks:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"641\" height=\"45\" data-attachment-id=\"258\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/two-freed-list-from-oldest\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-from-oldest.png?fit=641%2C45&amp;ssl=1\" data-orig-size=\"641,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"two-freed-list-from-oldest\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-from-oldest.png?fit=641%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-from-oldest.png?resize=641%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. Older nodes point to newer ones. The first and third nodes (i.e., the oldest and the third oldest\/second newest) have been deallocated and are labeled with the In use\" class=\"wp-image-258\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-from-oldest.png?w=641&amp;ssl=1 641w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/two-freed-list-from-oldest.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>This time, the first block will be reused:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"641\" height=\"45\" data-attachment-id=\"259\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/one-reused-list-from-oldest\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-from-oldest.png?fit=641%2C45&amp;ssl=1\" data-orig-size=\"641,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"one-reused-list-from-oldest\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-from-oldest.png?fit=641%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-from-oldest.png?resize=641%2C45&#038;ssl=1\" alt=\"Linked list with four nodes. Older nodes point to newer ones. The third node (i.e., the oldest and third oldest\/second newest) has been deallocated. Hence, it is labeled with the word Free\" class=\"wp-image-259\" style=\"width:630px;height:auto\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-from-oldest.png?w=641&amp;ssl=1 641w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/one-reused-list-from-oldest.png?resize=300%2C21&amp;ssl=1 300w\" sizes=\"auto, (max-width: 709px) 85vw, (max-width: 909px) 67vw, (max-width: 984px) 61vw, (max-width: 1362px) 45vw, 600px\" \/><\/figure>\n\n\n\n<p>Now, when we free the last block, we will have two free blocks at the top, allowing us to reduce the heap by two 8-byte blocks:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"313\" height=\"45\" data-attachment-id=\"262\" data-permalink=\"https:\/\/suspensao.blog.br\/disbelief\/implementing-malloc-and-free-old-memory-reused-first\/all-blocks-used-2\/\" data-orig-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/all-blocks-used-2.png?fit=313%2C45&amp;ssl=1\" data-orig-size=\"313,45\" data-comments-opened=\"1\" data-image-meta=\"{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}\" data-image-title=\"all-blocks-used-2\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/all-blocks-used-2.png?fit=313%2C45&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/all-blocks-used-2.png?resize=313%2C45&#038;ssl=1\" alt=\"Linked list with two nodes. We have freed two newer nodes, and since we reused the oldest, we have less nodes than the original case now.\" class=\"wp-image-262\" srcset=\"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/all-blocks-used-2.png?w=313&amp;ssl=1 313w, https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/all-blocks-used-2.png?resize=300%2C43&amp;ssl=1 300w\" sizes=\"auto, (max-width: 313px) 85vw, 313px\" \/><\/figure>\n\n\n\n<p>This example illustrates how, by giving preference to newer blocks, we end up accumulating old unused blocks, wasting memory and leading to unnecessary heap growth. The solution is to modify the search strategy, prioritizing the reuse of older blocks.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing preference for old blocks<\/h3>\n\n\n\n<p>To solve this problem, we will start by adding a pointer to the next block in the header. We will also create a global pointer to the first block, so we can start the search from it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>typedef struct Header { <br>  struct Header *previous, *next; <br>  size_t size; <br>  bool available; <br>} Header; <br><br>Header *first = NULL; <br>Header *last = NULL;<\/code><\/pre>\n\n\n\n<p>We will create memory blocks with headers in two different situations, so let&#8217;s make a small refactoring: we will extract this logic to a helper function that allocates and initializes the header (including setting the field <code>next<\/code>with <code>NULL<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Header *header_new(Header *previous, size_t size, bool available) { <br>  Header *header = sbrk(sizeof(Header) + size); <br>  header-&gt;previous = previous; <br>  header-&gt;next = NULL; <br>  header-&gt;size = size; <br>  header-&gt;available = false; <br>  return header; <br>}<\/code><\/pre>\n\n\n\n<p>With this new function, we can simplify the logic within <code>abmalloc()<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void *abmalloc(size_t size) { <br>  if (size == 0) { <br>    return NULL; <br>  } <br>  Header *header = last; <br>  while (header != NULL) { <br>    if (header-&gt;available &amp;&amp; (header-&gt;size &gt;= size)) { <br>      header-&gt;available = false; <br>      return header + 1; <br>    } <br>    header = header-&gt;previous; <br>  } <br>  last = header_new(last, size, false); <br>  return last + 1; <br>}<\/code><\/pre>\n\n\n\n<p>Now we have access to the first and last blocks, and given a block, we can find out the previous and next ones. We also know that when the pointer to the first block is null, no blocks have been allocated yet. So in this case, we will allocate the block immediately, and initialize both first and last:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void *abmalloc(size_t size) { <br>  if (size == 0) { <br>    return NULL; <br>  } <br>  if (first == NULL) { <br>    first = last = header_new(NULL, size, false); <br>    return first + 1; <br>  }<\/code><\/pre>\n\n\n\n<p>If <code>first<\/code> is no longer <code>NULL<\/code>, there are already allocated blocks, so we will start searching for a reusable block. We will continue using the variable <code>header<\/code> as an iterator, but instead of starting with the most recent block, the search will start from the oldest:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  Header *header = first;<\/code><\/pre>\n\n\n\n<p>At each iteration, we will advance to the next block in the sequence, instead of going backwards to the previous block:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  while (header != NULL) { <br>    if (header-&gt;available &amp;&amp; (header-&gt;size &gt;= size)) { <br>      header-&gt;available = false; <br>      return header + 1; <br>    } <br>    header = header-&gt;next; <br>  }<\/code><\/pre>\n\n\n\n<p>The logic remains the same: if we find an available block of sufficient size, it is returned. Otherwise, if no reusable block is found after we traverse the list, a new block is allocated:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  last = header_new(last, size, false);<\/code><\/pre>\n\n\n\n<p>Now, we need to adjust the block that was the last one (after the allocation, the second to last). It pointed to <code>NULL<\/code>, but now it should point to the new block. To do this, we set the previous block\u2019s <code>next<\/code> field to the new last block:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  last-&gt;previous-&gt;next = last; <br>  return last + 1; <br>}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Adjustments in the <code>abfree()<\/code> function<\/h3>\n\n\n\n<p>The function <code>abfree()<\/code> basically maintains the same structure, but now we must handle some edge cases. When we free blocks at the top of the heap, a new block becomes the last one, as we already do in this snippet:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    last = header-&gt;previous; <br>    brk(header)<\/code><\/pre>\n\n\n\n<p>Here, the pointer <code>header<\/code> references the last non-null block available on the stack. We have two possible scenarios:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>the current block has a previous block, which will become the new last block. In this case, we should set the pointer <code>next<\/code>of this block to <code>NULL<\/code>. <\/li>\n\n\n\n<li>the current block does not have a previous block (i.e., it is the first and oldest block). When it is freed, the stack is empty. In this case, instead of trying to update a field of a non-existent block, we simply set the variable <code>first<\/code> to <code>NULL<\/code>, indicating that there are no more allocated blocks.<\/li>\n<\/ol>\n\n\n\n<p>Here is how we implement it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>  last = header-&gt;previous; <br>  if (last != NULL) { <br>    last-&gt;next = NULL; <br>  } else { <br>    first = NULL; <br>  } <br>  brk(header);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>Our functions <code>abmalloc()<\/code> and <code>abfree()<\/code> now look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>        <code>typedef struct Header {\n  struct Header *previous, *next;\n  size_t size;\n  bool available;\n} Header;\n\nHeader *first = NULL;\nHeader *last = NULL;\n\nHeader *header_new(Header *previous, size_t size, bool available) {\n  Header *header = sbrk(sizeof(Header) + size);\n  header-&gt;previous = previous;\n  header-&gt;next = NULL;\n  header-&gt;size = size;\n  header-&gt;available = false;\n  return header;\n}\n\nvoid *abmalloc(size_t size) {\n  if (size == 0) {\n    return NULL;\n  }\n  if (first == NULL) {\n    first = last = header_new(NULL, size, false);\n    return first + 1;\n  }\n  Header *header = first;\n  while (header != NULL) {\n    if (header-&gt;available &amp;&amp; (header-&gt;size &gt;= size)) {\n      header-&gt;available = false;\n      return header + 1;\n    }\n    header = header-&gt;next;\n  }\n  last = header_new(last, size, false);\n  last-&gt;previous-&gt;next = last;\n  return last + 1;\n}\n\nvoid abfree(void *ptr) {\n  if (ptr == NULL) {\n   return;\n  }\n  Header *header = (Header*) ptr - 1;\n  if (header == last) {\n    while ((header-&gt;previous != NULL) &amp;&amp; header-&gt;previous-&gt;available) {\n      header = header-&gt;previous;\n    }\n    last = header-&gt;previous;\n    if (last != NULL) {\n      last-&gt;next = NULL;\n    } else {\n      first = NULL;\n    }\n    brk(header);\n  } else {\n   header-&gt;available = true;\n  }\n }<\/code><small>Code language:  PHP  ( php )<\/small><\/code><\/pre>\n\n\n\n<p>This change allows us to save considerably more memory. There are, however, still problems to solve. For example, consider the following scenario: we request the allocation of a memory block of 8 bytes, and <code>abmalloc()<\/code>reuse a block of, say, 1024 bytes. There is clearly a waste.<\/p>\n\n\n\n<p>We will see how to solve this in the next post.<\/p>\n\n\n\n<p><em>(This post is a translation of <\/em><a href=\"https:\/\/suspensao.blog.br\/descrenca\/implementando-malloc-e-free-memoria-antiga-tem-preferencia\/\">Implementando malloc() e free() \u2014 mem\u00f3ria antiga tem prefer\u00eancia<\/a><em>, first published in <a href=\"https:\/\/suspensao.blog.br\/descrenca\/\">Suspens\u00e3o de Descren\u00e7a<\/a>.)<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Suppose you have a linked list of blocks of memory that can be reused. Should you look for one to reuse from the beginning or the end? In this post, we have the answer, explain why and show how to implement it.<\/p>\n","protected":false},"author":1,"featured_media":264,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"Suppose you have a linked list of blocks of memory that can be reused. Should you look for one to reuse from the beginning or the end? In this post, we have the answer, explain why and show how to implement it.","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[75,76],"tags":[77,86,82,80,78,47],"class_list":["post-246","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c","category-linux","tag-c","tag-libc","tag-linux","tag-malloc","tag-memory-management","tag-software-development"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/suspensao.blog.br\/disbelief\/wp-content\/uploads\/2024\/09\/The-lower-part-of-the-Sanaa-manuscript-which-was-scrapped-and-written-over-an-original-text.-An-old-and-reused-parchment-1.jpg?fit=1077%2C480&ssl=1","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/p9Ru6q-3Y","jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/posts\/246","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/comments?post=246"}],"version-history":[{"count":12,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/posts\/246\/revisions"}],"predecessor-version":[{"id":276,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/posts\/246\/revisions\/276"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/media\/264"}],"wp:attachment":[{"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/media?parent=246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/categories?post=246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/suspensao.blog.br\/disbelief\/wp-json\/wp\/v2\/tags?post=246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}