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 中国語 Web サイトの他の関連記事を参照してください。

オブジェクト指向プログラミング(OOP)のC#とCの実装と機能には大きな違いがあります。 1)C#のクラス定義と構文はより簡潔であり、LINQなどの高度な機能をサポートします。 2)Cは、システムプログラミングと高性能のニーズに適した、より細かい粒状制御を提供します。どちらにも独自の利点があり、選択は特定のアプリケーションシナリオに基づいている必要があります。

XMLからCへの変換とデータ操作の実行は、次の手順で達成できます。1)TinyXML2ライブラリを使用してXMLファイルを解析する、2)データのデータ構造にデータをマッピングし、3)データ操作のためのSTD :: VectorなどのC標準ライブラリを使用します。これらの手順を通じて、XMLから変換されたデータを処理および効率的に操作できます。

C#は自動ガベージコレクションメカニズムを使用し、Cは手動メモリ管理を使用します。 1。C#のゴミコレクターは、メモリを自動的に管理してメモリの漏れのリスクを減らしますが、パフォーマンスの劣化につながる可能性があります。 2.Cは、微細な管理を必要とするアプリケーションに適した柔軟なメモリ制御を提供しますが、メモリの漏れを避けるためには注意して処理する必要があります。

Cは、現代のプログラミングにおいて依然として重要な関連性を持っています。 1)高性能および直接的なハードウェア操作機能により、ゲーム開発、組み込みシステム、高性能コンピューティングの分野で最初の選択肢になります。 2)豊富なプログラミングパラダイムとスマートポインターやテンプレートプログラミングなどの最新の機能は、その柔軟性と効率を向上させます。学習曲線は急ですが、その強力な機能により、今日のプログラミングエコシステムでは依然として重要です。

C学習者と開発者は、Stackoverflow、RedditのR/CPPコミュニティ、CourseraおよびEDXコース、Github、Professional Consulting Services、およびCPPCONのオープンソースプロジェクトからリソースとサポートを得ることができます。 1. StackOverFlowは、技術的な質問への回答を提供します。 2。RedditのR/CPPコミュニティが最新ニュースを共有しています。 3。CourseraとEDXは、正式なCコースを提供します。 4. LLVMなどのGitHubでのオープンソースプロジェクトやスキルの向上。 5。JetBrainやPerforceなどの専門的なコンサルティングサービスは、技術サポートを提供します。 6。CPPCONとその他の会議はキャリアを助けます

C#は、開発効率とクロスプラットフォームのサポートを必要とするプロジェクトに適していますが、Cは高性能で基礎となるコントロールを必要とするアプリケーションに適しています。 1)C#は、開発を簡素化し、ガベージコレクションとリッチクラスライブラリを提供します。これは、エンタープライズレベルのアプリケーションに適しています。 2)Cは、ゲーム開発と高性能コンピューティングに適した直接メモリ操作を許可します。

C継続的な使用の理由には、その高性能、幅広いアプリケーション、および進化する特性が含まれます。 1)高効率パフォーマンス:Cは、メモリとハードウェアを直接操作することにより、システムプログラミングと高性能コンピューティングで優れたパフォーマンスを発揮します。 2)広く使用されている:ゲーム開発、組み込みシステムなどの分野での輝き。3)連続進化:1983年のリリース以来、Cは競争力を維持するために新しい機能を追加し続けています。

CとXMLの将来の開発動向は次のとおりです。1)Cは、プログラミングの効率とセキュリティを改善するためのC 20およびC 23の標準を通じて、モジュール、概念、CORoutinesなどの新しい機能を導入します。 2)XMLは、データ交換および構成ファイルの重要なポジションを引き続き占有しますが、JSONとYAMLの課題に直面し、XMLSchema1.1やXpath3.1の改善など、より簡潔で簡単な方向に発展します。


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SecLists
SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

DVWA
Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
