{"id":13812250,"url":"https://github.com/rhempel/umm_malloc","last_synced_at":"2026-04-17T03:35:24.271Z","repository":{"id":27907150,"uuid":"31398957","full_name":"rhempel/umm_malloc","owner":"rhempel","description":"Memory Manager For Small(ish) Microprocessors","archived":false,"fork":false,"pushed_at":"2025-02-25T17:54:50.000Z","size":233,"stargazers_count":423,"open_issues_count":5,"forks_count":108,"subscribers_count":28,"default_branch":"main","last_synced_at":"2025-05-14T21:52:28.605Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rhempel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2015-02-27T02:06:46.000Z","updated_at":"2025-05-13T16:55:42.000Z","dependencies_parsed_at":"2024-01-14T07:58:46.455Z","dependency_job_id":"23213145-676a-422a-943a-fa02e7ec7b69","html_url":"https://github.com/rhempel/umm_malloc","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/rhempel/umm_malloc","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rhempel%2Fumm_malloc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rhempel%2Fumm_malloc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rhempel%2Fumm_malloc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rhempel%2Fumm_malloc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rhempel","download_url":"https://codeload.github.com/rhempel/umm_malloc/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rhempel%2Fumm_malloc/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31913783,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-16T18:22:33.417Z","status":"online","status_checked_at":"2026-04-17T02:00:06.879Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-04T04:00:49.875Z","updated_at":"2026-04-17T03:35:24.263Z","avatar_url":"https://github.com/rhempel.png","language":"C","funding_links":[],"categories":["工具、材料","Memory","memory manager"],"sub_categories":["软件：嵌入式操作系统、驱动、GUI 库等","Memory management","dynamic malloc"],"readme":"[![verifyer](https://github.com/rhempel/umm_malloc/actions/workflows/verifier.yml/badge.svg?branch=master)](https://github.com/rhempel/umm_malloc/actions/workflows/verifier.yml)\n\n# umm_malloc - Memory Manager For Small(ish) Microprocessors\n\nThis is a memory management library specifically designed to work with the\nARM7 embedded processor, but it should work on many other 32 bit processors,\nas well as 16 and 8 bit devices.\n\nYou can even use it on a bigger project where a single process might want\nto manage a large number of smaller objects, and using the system heap\nmight get expensive.\n\n## Acknowledgements\n\nJoerg Wunsch and the avr-libc provided the first `malloc()` implementation\nthat I examined in detail.\n\n`http://www.nongnu.org/avr-libc`\n\nDoug Lea's paper on malloc() was another excellent reference and provides\na lot of detail on advanced memory management techniques such as binning.\n\n`http://gee.cs.oswego.edu/dl/html/malloc.html`\n\nBill Dittman provided excellent suggestions, including macros to support\nusing these functions in critical sections, and for optimizing `realloc()`\nfurther by checking to see if the previous block was free and could be \nused for the new block size. This can help to reduce heap fragmentation\nsignificantly. \n\nYaniv Ankin suggested that a way to dump the current heap condition\nmight be useful. I combined this with an idea from plarroy to also\nallow checking a free pointer to make sure it's valid.\n\nDimitry Frank contributed many helpful additions to make things more\nrobust including a user specified config file and a method of testing\nthe integrity of the data structures.\n\nGitHub user @devyte provided useful feedback on the nesting of functions\nas well as a fix for the problem that separates out the core free and\nmalloc functionality.\n\nGitHub users @d-a-v and @devyte provided great input on establishing\na heap fragmentation metric which they graciously allowed to be used\nin umm_malloc.\n\nKatherine Whitlock (@stellar-aria) extended the library for usage in \nscenarios where more than one heap or memory space is needed.\n\n## Usage\n\nThis library is designed to be included in your application as a\nsubmodule that has default configuration that can be overridden\nas needed by your application code.\n\nThe `umm_malloc` library can be initialized two ways. The first is\nat link time:\n\n- Set `UMM_MALLOC_CFG_HEAP_ADDR` to the symbol representing\n  the starting address of the heap. The heap must be\n  aligned on the natural boundary size of the processor.\n- Set `UMM_MALLOC_CFG_HEAP_SIZE` to the size of the heap in bytes.\n  The heap size must be a multiple of the natural boundary size of\n  the processor.\n\nThis is how the `umm_init()` call handles initializing the heap.\n\nWe can also call `umm_init_heap(void *pheap, size_t size)` where the\nheap details are passed in manually. This is useful in systems where\nyou can allocate a block of memory at run time - for example in Rust.\n\n### Multiple heaps\n\nFor usage in a scenario that requires multiple heaps, the heap type\n`umm_heap` is exposed. All API functions (`malloc`, `free`, `realloc`, etc.) \nhave a corresponding `umm_multi_*` variant that take a pointer to this \ntype as their first parameter.\n\nMuch like standard initialization, there are two methods:\n   - `umm_multi_init(umm_heap *heap)`, which initializes a given heap\n    using linker symbols\n   - `umm_multi_init_heap(umm_heap *heap, void *ptr, size_t size)`, which\n    will initialize a given heap using a known address and size.\n\n## Automated Testing\n\n`umm_malloc` is designed to be testable in standalone\nmode using `ceedling`. To run the test suite, just make sure you have\n`ceedling` installed and then run:\n\n```\nceedling clean\nceedling test:all\n```\n\n## Configuration\n\n\u003e :warning: **You MUST provide a file called `umm_malloc_cfgport.h`\n\u003e somewhere in your app, even if it's blank**\n\nThe reason for this is the way the configuration override heirarchy\nworks. The priority for configuration overrides is as follows:\n\n1. Command line defines using `-D UMM_xxx`\n2. A custom config filename using `-D UMM_MALLOC_CFGFILE=\"\u003cfilename.cfg\u003e\"`\n3. The default config filename `path/to/config/umm_malloc_cfgport.h`\n4. The default configuration in `src/umm_malloc_cfg.h`\n\n\nThe following `#define`s are set to useful defaults in\n`src/umm_malloc_cfg.h` and can be overridden as needed.\n\nThe fit algorithm is defined as either:\n\n- `UMM_BEST_FIT` which scans the entire free list and looks\n   for either an exact fit or the smallest block that will\n   satisfy the request. This is the default fit method.\n- `UMM_FIRST_FIT` which scans the entire free list and looks\n   for the first block that satisfies the request.\n\nThe following `#define`s are disabled by default and should\nremain disabled for production use. They are helpful when \ntesting allocation errors (which are normally due to bugs in\nthe application code) or for running the test suite when\nmaking changes to the code.\n\n- `UMM_INFO` is used to include code that allows dumping\n  the entire heap structure (helpful when there's a problem).\n\n- `UMM_INTEGRITY_CHECK` is used to include code that\n  performs an integrity check on the heap structure. It's\n  up to you to call the `umm_integrity_check()` function.\n\n- `UMM_POISON_CHECK` is used to include code that\n  adds some bytes around the memory being allocated that\n  are filled with known data. If the data is not intact\n  when the block is checked, then somone has written outside\n  of the memory block they have been allocated. It is up\n  to you to call the `umm_poison_check()` function.\n\n## API\n\nThe following functions are available for your application:\n\n```c\nvoid *umm_malloc(size_t size)\nvoid *umm_calloc(size_t num, size_t size)\nvoid *umm_realloc(void *ptr, size_t size)\nvoid  umm_free(void *ptr)\n```\n\nThey have exactly the same semantics as the corresponding standard library\nfunctions.\n\nTo initialize the library there are two options:\n\n```c\nvoid  umm_init(void)\nvoid  umm_init_heap(void *ptr, size_t size)\n```\n\n### Multi-Heap API\n\nFor the case of multiple heaps, corresponding `umm_multi_*` functions are provided.\n\n```c\nvoid *umm_multi_malloc(umm_heap *heap, size_t size)\nvoid *umm_multi_calloc(umm_heap *heap, size_t num, size_t size)\nvoid *umm_multi_realloc(umm_heap *heap, void *ptr, size_t size)\nvoid  umm_multi_free(umm_heap *heap, void *ptr)\n```\n\nAs with the standard API, there are two options for initialization:\n\n```c\nvoid  umm_multi_init(umm_heap *heap)\nvoid  umm_multi_init_heap(umm_heap *heap, void *ptr, size_t size)\n```\n \n## Background\n\nThe memory manager assumes the following things:\n\n1. The standard POSIX compliant malloc/calloc/realloc/free semantics are used\n1. All memory used by the manager is allocated at link time, it is aligned\non a 32 bit boundary, it is contiguous, and its extent (start and end\naddress) is filled in by the linker.\n1. All memory used by the manager is initialized to 0 as part of the\nruntime startup routine. No other initialization is required.\n\nThe fastest linked list implementations use doubly linked lists so that\nits possible to insert and delete blocks in constant time. This memory\nmanager keeps track of both free and used blocks in a doubly linked list.\n\nMost memory managers use a list structure made up of pointers\nto keep track of used - and sometimes free - blocks of memory. In an\nembedded system, this can get pretty expensive as each pointer can use\nup to 32 bits.\n\nIn most embedded systems there is no need for managing a large quantity\nof memory block dynamically, so a full 32 bit pointer based data structure\nfor the free and used block lists is wasteful. A block of memory on\nthe free list would use 16 bytes just for the pointers!\n\nThis memory management library sees the heap as an array of blocks,\nand uses block numbers to keep track of locations. The block numbers are\n15 bits - which allows for up to 32767 blocks of memory. The high order\nbit marks a block as being either free or in use, which will be explained\nlater.\n\nThe result is that a block of memory on the free list uses just 8 bytes\ninstead of 16.\n\nIn fact, we go even one step futher when we realize that the free block\nindex values are available to store data when the block is allocated.\n\nThe overhead of an allocated block is therefore just 4 bytes.\n\nEach memory block holds 8 bytes, and there are up to 32767 blocks\navailable, for about 256K of heap space. If that's not enough, you\ncan always add more data bytes to the body of the memory block\nat the expense of free block size overhead.\n\nThere are a lot of little features and optimizations in this memory\nmanagement system that makes it especially suited to small systems, and\nthe best way to appreciate them is to review the data structures and\nalgorithms used, so let's get started.\n\n## Detailed Description\n\nWe have a general notation for a block that we'll use to describe the\ndifferent scenarios that our memory allocation algorithm must deal with:\n\n```\n   +----+----+----+----+\nc  |* n |  p | nf | pf |\n   +----+----+----+----+\n```\n\nWhere:\n\n- c  is the index of this block\n- *  is the indicator for a free block\n- n  is the index of the next block in the heap\n- p  is the index of the previous block in the heap\n- nf is the index of the next block in the free list\n- pf is the index of the previous block in the free list\n\nThe fact that we have forward and backward links in the block descriptors\nmeans that malloc() and free() operations can be very fast. It's easy\nto either allocate the whole free item to a new block or to allocate part\nof the free item and leave the rest on the free list without traversing\nthe list from front to back first.\n\nThe entire block of memory used by the heap is assumed to be initialized\nto 0. The very first block in the heap is special - it't the head of the\nfree block list. It is never assimilated with a free block (more on this\nlater).\n\nOnce a block has been allocated to the application, it looks like this:\n\n```\n  +----+----+----+----+\nc |  n |  p |   ...   |\n  +----+----+----+----+\n```\n\nWhere:\n\n- c  is the index of this block\n- n  is the index of the next block in the heap\n- p  is the index of the previous block in the heap\n\nNote that the free list information is gone because it's now\nbeing used to store actual data for the application. If we had\neven 500 items in use, that would be 2,000 bytes for\nfree list information. We simply can't afford to waste that much.\n\nThe address of the `...` area is what is returned to the application\nfor data storage.\n\nThe following sections describe the scenarios encountered during the\noperation of the library. There are two additional notation conventions:\n\n`??` inside a pointer block means that the data is irrelevant. We don't care\nabout it because we don't read or modify it in the scenario being\ndescribed.\n\n`...` between memory blocks indicates zero or more additional blocks are\nallocated for use by the upper block.\n\nWhile we're talking about \"upper\" and \"lower\" blocks, we should make\na comment about adresses. In the diagrams, a block higher up in the\npicture is at a lower address. And the blocks grow downwards their\nblock index increases as does their physical address.\n\nFinally, there's one very important characteristic of the individual\nblocks that make up the heap - there can never be two consecutive free\nmemory blocks, but there can be consecutive used memory blocks.\n\nThe reason is that we always want to have a short free list of the\nlargest possible block sizes. By always assimilating a newly freed block\nwith adjacent free blocks, we maximize the size of each free memory area.\n\n### Operation of malloc right after system startup\n\nAs part of the system startup code, all of the heap has been cleared.\n\nDuring the very first malloc operation, we start traversing the free list\nstarting at index 0. The index of the next free block is 0, which means\nwe're at the end of the list!\n\nAt this point, the malloc has a special test that checks if the current\nblock index is 0, which it is. This special case initializes the free\nlist to point at block index 1 and then points block 1 to the\nlast block (lf) on the heap.\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\n0  |  0 |  0 |  0 |  0 |           0  |  1 |  0 |  1 |  1 |\n   +----+----+----+----+              +----+----+----+----+\n                                      +----+----+----+----+\n                                   1  |*lf |  0 |  0 |  0 |\n                                      +----+----+----+----+\n                                               ...\n                                      +----+----+----+----+\n                                   lf |  0 |  1 |  0 |  0 |\n                                      +----+----+----+----+\n```\n\nThe heap is now ready to complete the first malloc operation.\n\n### Operation of malloc when we have reached the end of the free list and there is no block large enough to accommodate the request.\n\nThis happens at the very first malloc operation, or any time the free\nlist is traversed and no free block large enough for the request is\nfound.\n\nThe current block pointer will be at the end of the free list, and we\nknow we're at the end of the list because the nf index is 0, like this:\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\npf |*?? | ?? | cf | ?? |           pf |*?? | ?? | lf | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\n p | cf | ?? |   ...   |            p | cf | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+  \ncf |  0 |  p |  0 | pf |            c | lf |  p |   ...   | \n   +----+----+----+----+              +----+----+----+----+\n                                      +----+----+----+----+\n                                   lf |  0 | cf |  0 | pf |\n                                      +----+----+----+----+\n```\n\nAs we walk the free list looking for a block of size b or larger, we get\nto cf, which is the last item in the free list. We know this because the\nnext index is 0.\n\nSo we're going to turn cf into the new block of memory, and then create\na new block that represents the last free entry (lf) and adjust the prev\nindex of lf to point at the  block we just created. We also need to adjust\nthe next index of the new block (c) to point to the last free block.\n\nNote that the next free index of the pf block must point to the new lf\nbecause cf is no longer a free block!\n\n### Operation of malloc when we have found a block (cf) that will fit the current request of b units exactly\n\nThis one is pretty easy, just clear the free list bit in the current\nblock and unhook it from the free list.\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\npf |*?? | ?? | cf | ?? |           pf |*?? | ?? | nf | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\n p | cf | ?? |   ...   |            p | cf | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+  Clear the free\ncf |* n |  p | nf | pf |           cf |  n |  p |   ..    |  list bit here\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n n | ?? | cf |   ...   |            n | ?? | cf |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? | cf |           nf | ?? | ?? | ?? | pf |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nUnhooking from the free list is accomplished by adjusting the next and\nprev free list index values in the pf and nf blocks.\n\n### Operation of malloc when we have found a block that will fit the current request of b units with some left over\n\nWe'll allocate the new block at the END of the current free block so we\ndon't have to change ANY free list pointers.\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\npf |*?? | ?? | cf | ?? |           pf |*?? | ?? | cf | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\n p | cf | ?? |   ...   |            p | cf | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\ncf |* n |  p | nf | pf |           cf |* c |  p | nf | pf |\n   +----+----+----+----+              +----+----+----+----+\n                                      +----+----+----+----+ This is the new\n                                    c |  n | cf |   ..    | block at cf+b\n                                      +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n n | ?? | cf |   ...   |            n | ?? |  c |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? | cf |           nf | ?? | ?? | ?? | pf |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nThis one is prety easy too, except we don't need to mess with the\nfree list indexes at all becasue we'll allocate the new block at the\nend of the current free block. We do, however have to adjust the\nindexes in cf, c, and n.\n\nThat covers the initialization and all possible malloc scenarios, so now\nwe need to cover the free operation possibilities...\n\n### Free Scenarios\n\nThe operation of free depends on the position of the current block being\nfreed relative to free list items immediately above or below it. The code\nworks like this:\n\n```\nif next block is free\n    assimilate with next block already on free list\nif prev block is free\n    assimilate with prev block already on free list\nelse\n    put current block at head of free list\n```\n\nStep 1 of the free operation checks if the next block is free, and if it\nis assimilate the next block with this one.\n\nNote that c is the block we are freeing up, cf is the free block that\nfollows it.\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\npf |*?? | ?? | cf | ?? |           pf |*?? | ?? | nf | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\n p |  c | ?? |   ...   |            p |  c | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+ This block is\n c | cf |  p |   ...   |            c | nn |  p |   ...   | disconnected\n   +----+----+----+----+              +----+----+----+----+ from free list,\n   +----+----+----+----+                                    assimilated with\ncf |*nn |  c | nf | pf |                                    the next, and\n   +----+----+----+----+                                    ready for step 2\n   +----+----+----+----+              +----+----+----+----+\nnn | ?? | cf | ?? | ?? |           nn | ?? |  c |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? | cf |           nf |*?? | ?? | ?? | pf |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nTake special note that the newly assimilated block (c) is completely\ndisconnected from the free list, and it does not have its free list\nbit set. This is important as we move on to step 2 of the procedure...\n\nStep 2 of the free operation checks if the prev block is free, and if it\nis then assimilate it with this block.\n\nNote that c is the block we are freeing up, pf is the free block that\nprecedes it.\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+ This block has\npf |* c | ?? | nf | ?? |           pf |* n | ?? | nf | ?? | assimilated the\n   +----+----+----+----+              +----+----+----+----+ current block\n   +----+----+----+----+\n c |  n | pf |   ...   |\n   +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n n | ?? |  c |   ...   |            n | ?? | pf | ?? | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? | pf |           nf |*?? | ?? | ?? | pf |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nNothing magic here, except that when we're done, the current block (c)\nis gone since it's been absorbed into the previous free block. Note that\nthe previous step guarantees that the next block (n) is not free.\n\nStep 3 of the free operation only runs if the previous block is not free.\nit just inserts the current block to the head of the free list.\n\nRemember, 0 is always the first block in the memory heap, and it's always\nhead of the free list!\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\n 0 | ?? | ?? | nf |  0 |            0 | ?? | ?? |  c |  0 |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\n p |  c | ?? |   ...   |            p |  c | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n c |  n |  p |   ..    |            c |* n |  p | nf |  0 |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n n | ?? |  c |   ...   |            n | ?? |  c |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? |  0 |           nf |*?? | ?? | ?? |  c |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nAgain, nothing spectacular here, we're simply adjusting a few pointers\nto make the most recently freed block the first item in the free list.\n\nThat's because finding the previous free block would mean a reverse\ntraversal of blocks until we found a free one, and it's just easier to\nput it at the head of the list. No traversal is needed.\n\n### Realloc Scenarios\n\nFinally, we can cover realloc, which has the following basic operation.\n\nThe first thing we do is assimilate up with the next free block of\nmemory if possible. This step might help if we're resizing to a bigger\nblock of memory. It also helps if we're downsizing and creating a new\nfree block with the leftover memory.\n\nFirst we check to see if the next block is free, and we assimilate it\nto this block if it is. If the previous block is also free, and if\ncombining it with the current block would satisfy the request, then we\nassimilate with that block and move the current data down to the new\nlocation.\n\nAssimilating with the previous free block and moving the data works\nlike this:\n\n```\n   BEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\npf |*?? | ?? | cf | ?? |           pf |*?? | ?? | nf | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\ncf |* c | ?? | nf | pf |            c |  n | ?? |   ...   | The data gets\n   +----+----+----+----+              +----+----+----+----+ moved from c to\n   +----+----+----+----+                                    the new data area  \n c |  n | cf |   ...   |                                    in cf, then c is\n   +----+----+----+----+                                    adjusted to cf\n   +----+----+----+----+              +----+----+----+----+\n n | ?? |  c |   ...   |            n | ?? |  c | ?? | ?? |\n   +----+----+----+----+              +----+----+----+----+\n            ...                                ...\n   +----+----+----+----+              +----+----+----+----+\nnf |*?? | ?? | ?? | cf |           nf |*?? | ?? | ?? | pf |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nOnce we're done that, there are three scenarios to consider:\n\n1. The current block size is exactly the right size, so no more work is\nneeded.\n\n2. The current block is bigger than the new required size, so carve off\nthe excess and add it to the free list.\n\n3. The current block is still smaller than the required size, so malloc\na new block of the correct size and copy the current data into the new\nblock before freeing the current block.\n\nThe only one of these scenarios that involves an operation that has not\nyet been described is the second one, and it's shown below:\n\n```\nBEFORE                             AFTER\n\n   +----+----+----+----+              +----+----+----+----+\n p |  c | ?? |   ...   |            p |  c | ?? |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n   +----+----+----+----+              +----+----+----+----+\n c |  n |  p |   ...   |            c |  s |  p |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n                                      +----+----+----+----+ This is the\n                                    s |  n |  c |   ..    | new block at\n                                      +----+----+----+----+ c+blocks\n   +----+----+----+----+              +----+----+----+----+\n n | ?? |  c |   ...   |            n | ?? |  s |   ...   |\n   +----+----+----+----+              +----+----+----+----+\n```\n\nThen we call free() with the adress of the data portion of the new\nblock (s) which adds it to the free list.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frhempel%2Fumm_malloc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frhempel%2Fumm_malloc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frhempel%2Fumm_malloc/lists"}