ホームページ バックエンド開発 C++ malloc() と free() の実装 — 古いメモリが最初に再利用されます

malloc() と free() の実装 — 古いメモリが最初に再利用されます

Oct 11, 2024 am 10:12 AM

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:

Implementing malloc() and free() — old memory reused first

Now, we release the first and third blocks…

abfree(ptr1);
abfree(ptr3);
ログイン後にコピー

…resulting in the following structure:

Implementing malloc() and free() — old memory reused first

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:

Implementing malloc() and free() — old memory reused first

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:

Implementing malloc() and free() — old memory reused first

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…

Implementing malloc() and free() — old memory reused first

…and again we free the first and third memory blocks:

Implementing malloc() and free() — old memory reused first

This time, the first block will be reused:

Implementing malloc() and free() — old memory reused first

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:

Implementing malloc() and free() — old memory reused first

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:

  1. 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.
  2. 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 サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

C#対C:歴史、進化、将来の見通し C#対C:歴史、進化、将来の見通し Apr 19, 2025 am 12:07 AM

C#とCの歴史と進化はユニークであり、将来の見通しも異なります。 1.Cは、1983年にBjarnestrostrupによって発明され、オブジェクト指向のプログラミングをC言語に導入しました。その進化プロセスには、C 11の自動キーワードとラムダ式の導入など、複数の標準化が含まれます。C20概念とコルーチンの導入、将来のパフォーマンスとシステムレベルのプログラミングに焦点を当てます。 2.C#は2000年にMicrosoftによってリリースされました。CとJavaの利点を組み合わせて、その進化はシンプルさと生産性に焦点を当てています。たとえば、C#2.0はジェネリックを導入し、C#5.0は非同期プログラミングを導入しました。これは、将来の開発者の生産性とクラウドコンピューティングに焦点を当てます。

C#対C:学習曲線と開発者エクスペリエンス C#対C:学習曲線と開発者エクスペリエンス Apr 18, 2025 am 12:13 AM

C#とCおよび開発者の経験の学習曲線には大きな違いがあります。 1)C#の学習曲線は比較的フラットであり、迅速な開発およびエンタープライズレベルのアプリケーションに適しています。 2)Cの学習曲線は急勾配であり、高性能および低レベルの制御シナリオに適しています。

Cの静的分析とは何ですか? Cの静的分析とは何ですか? Apr 28, 2025 pm 09:09 PM

Cでの静的分析の適用には、主にメモリ管理の問題の発見、コードロジックエラーの確認、およびコードセキュリティの改善が含まれます。 1)静的分析では、メモリリーク、ダブルリリース、非初期化ポインターなどの問題を特定できます。 2)未使用の変数、死んだコード、論理的矛盾を検出できます。 3)カバー性などの静的分析ツールは、バッファーオーバーフロー、整数のオーバーフロー、安全でないAPI呼び出しを検出して、コードセキュリティを改善します。

CおよびXML:関係とサポートの調査 CおよびXML:関係とサポートの調査 Apr 21, 2025 am 12:02 AM

Cは、サードパーティライブラリ(TinyXML、PUGIXML、XERCES-Cなど)を介してXMLと相互作用します。 1)ライブラリを使用してXMLファイルを解析し、それらをC処理可能なデータ構造に変換します。 2)XMLを生成するときは、Cデータ構造をXML形式に変換します。 3)実際のアプリケーションでは、XMLが構成ファイルとデータ交換に使用されることがよくあり、開発効率を向上させます。

CでChronoライブラリを使用する方法は? CでChronoライブラリを使用する方法は? Apr 28, 2025 pm 10:18 PM

CでChronoライブラリを使用すると、時間と時間の間隔をより正確に制御できます。このライブラリの魅力を探りましょう。 CのChronoライブラリは、時間と時間の間隔に対処するための最新の方法を提供する標準ライブラリの一部です。 Time.HとCtimeに苦しんでいるプログラマーにとって、Chronoは間違いなく恩恵です。コードの読みやすさと保守性を向上させるだけでなく、より高い精度と柔軟性も提供します。基本から始めましょう。 Chronoライブラリには、主に次の重要なコンポーネントが含まれています。STD:: Chrono :: System_Clock:現在の時間を取得するために使用されるシステムクロックを表します。 STD :: Chron

Cの未来:適応と革新 Cの未来:適応と革新 Apr 27, 2025 am 12:25 AM

Cの将来は、並列コンピューティング、セキュリティ、モジュール化、AI/機械学習に焦点を当てます。1)並列コンピューティングは、コルーチンなどの機能を介して強化されます。 2)セキュリティは、より厳格なタイプのチェックとメモリ管理メカニズムを通じて改善されます。 3)変調は、コード組織とコンパイルを簡素化します。 4)AIと機械学習は、数値コンピューティングやGPUプログラミングサポートなど、CにComply Coveに適応するように促します。

C:それは死にかけていますか、それとも単に進化していますか? C:それは死にかけていますか、それとも単に進化していますか? Apr 24, 2025 am 12:13 AM

c isnotdying; it'sevolving.1)c relelevantdueToitsversitileSileSixivisityinperformance-criticalApplications.2)thelanguageSlikeModulesandCoroutoUtoimveUsablive.3)despiteChallen

C#対C:メモリ管理とガベージコレクション C#対C:メモリ管理とガベージコレクション Apr 15, 2025 am 12:16 AM

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

See all articles