实现 malloc() 和 free() — 首先重用旧内存
In the previous post in this series on implementing malloc() and free(), 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’s break it down.
Heap reduction by reusing recent blocks
Consider the following scenario. First, we allocate four memory blocks:
void *ptr1 = abmalloc(8); void *ptr2 = abmalloc(8); void *ptr3 = abmalloc(8); void *ptr4 = abmalloc(8);
The memory structure can be visualized like this:
Now, we release the first and third blocks…
abfree(ptr1); abfree(ptr3);
…resulting in the following structure:
Then we allocate another block of the same size:
void *ptr5 = abmalloc(8);
As the function abmalloc() starts searching for the most recent free block, it reuses the block at the top. If we now free the last block:
If we now release the last block…
abfree(ptr4);
…we can reduce the heap size by just one 8-byte block, since the previous block is no longer free:
Reuse of old blocks
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…
…and again we free the first and third memory blocks:
This time, the first block will be reused:
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:
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.
Implementing preference for old blocks
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:
typedef struct Header { struct Header *previous, *next; size_t size; bool available; } Header; Header *first = NULL; Header *last = NULL;
We will create memory blocks with headers in two different situations, so let’s make a small refactoring: we will extract this logic to a helper function that allocates and initializes the header (including setting the field nextwith NULL):
Header *header_new(Header *previous, size_t size, bool available) { Header *header = sbrk(sizeof(Header) + size); header->previous = previous; header->next = NULL; header->size = size; header->available = false; return header; }
With this new function, we can simplify the logic within abmalloc():
void *abmalloc(size_t size) { if (size == 0) { return NULL; } Header *header = last; while (header != NULL) { if (header->available && (header->size >= size)) { header->available = false; return header + 1; } header = header->previous; } last = header_new(last, size, false); return last + 1; }
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:
void *abmalloc(size_t size) { if (size == 0) { return NULL; } if (first == NULL) { first = last = header_new(NULL, size, false); return first + 1; }
If firstit is no longer NULL, there are already allocated blocks, so we will start searching for a reusable block. We will continue using the variable headeras an iterator, but instead of starting with the most recent block, the search will start from the oldest:
Header *header = first;
At each iteration, we will advance to the next block in the sequence, instead of going backwards to the previous block:
while (header != NULL) { if (header->available && (header->size >= size)) { header->available = false; return header + 1; } header = header->next; }
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:
last = header_new(last, size, false);
Now, we need to adjust the block that was the last one (after the allocation, the second to last). It pointed to NULL, but now it should point to the new block. To do this, we set the previous block’s next field to the new last block:
last->previous->next = last; return last + 1; }
Adjustments in abfree()
The function abfree() 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:
last = header->previous; brk(header)
Here, the pointer header references the last non-null block available on the stack. We have two possible scenarios:
- the current block has a previous block, which will become the new last block. In this case, we should set the pointer nextof this block to NULL.
- 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 it first to NULL, indicating that there are no more allocated blocks.
Here is how we implement it:
last = header->previous; if (last != NULL) { last->next = NULL; } else { first = NULL; } brk(header);
Conclusion
Our functions abmalloc() and abfree() now look like this:
typedef struct Header { struct Header *previous, *next; size_t size; bool available; } Header; Header *first = NULL; Header *last = NULL; Header *header_new(Header *previous, size_t size, bool available) { Header *header = sbrk(sizeof(Header) + size); header->previous = previous; header->next = NULL; header->size = size; header->available = false; return header; } void *abmalloc(size_t size) { if (size == 0) { return NULL; } if (first == NULL) { first = last = header_new(NULL, size, false); return first + 1; } Header *header = first; while (header != NULL) { if (header->available && (header->size >= size)) { header->available = false; return header + 1; } header = header->next; } last = header_new(last, size, false); last->previous->next = last; return last + 1; } void abfree(void *ptr) { if (ptr == NULL) { return; } Header *header = (Header*) ptr - 1; if (header == last) { while ((header->previous != NULL) && header->previous->available) { header = header->previous; } last = header->previous; if (last != NULL) { last->next = NULL; } else { first = NULL; } brk(header); } else { header->available = true; } }
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 abmalloc() reuse a block of, say, 1024 bytes. There is clearly a waste.
We will see how to solve this in the next post.
以上是实现 malloc() 和 free() — 首先重用旧内存的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

C#和C 的历史与演变各有特色,未来前景也不同。1.C 由BjarneStroustrup在1983年发明,旨在将面向对象编程引入C语言,其演变历程包括多次标准化,如C 11引入auto关键字和lambda表达式,C 20引入概念和协程,未来将专注于性能和系统级编程。2.C#由微软在2000年发布,结合C 和Java的优点,其演变注重简洁性和生产力,如C#2.0引入泛型,C#5.0引入异步编程,未来将专注于开发者的生产力和云计算。

C 适合系统编程和硬件交互,因为它提供了接近硬件的控制能力和面向对象编程的强大特性。1)C 通过指针、内存管理和位操作等低级特性,实现高效的系统级操作。2)硬件交互通过设备驱动程序实现,C 可以编写这些驱动程序,处理与硬件设备的通信。

C 和XML的未来发展趋势分别为:1)C 将通过C 20和C 23标准引入模块、概念和协程等新特性,提升编程效率和安全性;2)XML将继续在数据交换和配置文件中占据重要地位,但会面临JSON和YAML的挑战,并朝着更简洁和易解析的方向发展,如XMLSchema1.1和XPath3.1的改进。

C 持续使用的理由包括其高性能、广泛应用和不断演进的特性。1)高效性能:通过直接操作内存和硬件,C 在系统编程和高性能计算中表现出色。2)广泛应用:在游戏开发、嵌入式系统等领域大放异彩。3)不断演进:自1983年发布以来,C 持续增加新特性,保持其竞争力。

C 多线程和并发编程的核心概念包括线程的创建与管理、同步与互斥、条件变量、线程池、异步编程、常见错误与调试技巧以及性能优化与最佳实践。1)创建线程使用std::thread类,示例展示了如何创建并等待线程完成。2)同步与互斥使用std::mutex和std::lock_guard保护共享资源,避免数据竞争。3)条件变量通过std::condition_variable实现线程间的通信和同步。4)线程池示例展示了如何使用ThreadPool类并行处理任务,提高效率。5)异步编程使用std::as

C 通过第三方库(如TinyXML、Pugixml、Xerces-C )与XML交互。1)使用库解析XML文件,将其转换为C 可处理的数据结构。2)生成XML时,将C 数据结构转换为XML格式。3)在实际应用中,XML常用于配置文件和数据交换,提升开发效率。

C 的内存管理、指针和模板是核心特性。1.内存管理通过new和delete手动分配和释放内存,需注意堆和栈的区别。2.指针允许直接操作内存地址,使用需谨慎,智能指针可简化管理。3.模板实现泛型编程,提高代码重用性和灵活性,需理解类型推导和特化。

C 学习者和开发者可以从StackOverflow、Reddit的r/cpp社区、Coursera和edX的课程、GitHub上的开源项目、专业咨询服务以及CppCon等会议中获得资源和支持。1.StackOverflow提供技术问题的解答;2.Reddit的r/cpp社区分享最新资讯;3.Coursera和edX提供正式的C 课程;4.GitHub上的开源项目如LLVM和Boost提升技能;5.专业咨询服务如JetBrains和Perforce提供技术支持;6.CppCon等会议有助于职业
