シングルヘッダーアリーナアロケーター。 C89互換性。
arena.hへの変更アリーナアロケーターは、複数の割り当てをグループとして解放できるようにすることで、より簡単で高速でより安全な動的メモリ管理を実現する簡単な方法です。これは、大規模な領域にメモリを割り当て、必要に応じてそのメモリの一部を分散させて、 mallocコールの量を減らすことによって行われます(単純なポインター算術と比較して遅い)。
アリーナを破壊すると、それとそのすべての内容も解放され、遅いfreeコールの量が減ります。さらに進むと、メモリポインターを0にリセットするだけでアリーナをクリアでき、それらを再利用し、さらに多くのmallocとfreeの必要性を排除できます。
この素晴らしい記事を読むことで、Arena/Zone/Region Allocatorsの詳細を学ぶことができます。
これを短くします。私はそれを使用しているからではなく、楽しみのためにC89コンプライアンスを維持しています。私は個人的にC11の楽しみです。 C89が唯一の方法だと思うなら、まあ、あなたにとって良いことです!しかし、あなたは間違っています。
このプロジェクトを他のプログラマーと共有するたびに、私が受け取る最も一般的な応答の1つは、次の行に沿って何かです。私は3つの理由でこの声明を問題にします...
それは、時代遅れの、結果として、有害な構造がまだ教育システムで施行されていることを示しています。
この声明を出す人がそれを信じる実際の理由を非常にめったに持っていません。この人は、「ヘッダーファイルに実装/ロジックコードを決して入れないでください」と考えていますか?彼らがそれに同意することを選んだ理由の根拠なしに彼らが聞いたことを単に逆流させることは、私を決して助けません。
ヘッダーのみ/シングルヘッダーライブラリに対する最大かつ最も有効な批判は、ヘッダーを変更するには、それを含むすべてのファイルを再コンパイルする必要があることです。私のプロジェクトの場合、 arena.hを変更します。実際の実装は、 #defineのARENA_IMPLEMENTATION Macroという翻訳ユニットにのみ含まれているにもかかわらず、それを含むすべてのファイルの再構築をもたらします。解決策? arena.h目的の状態になったら、変更を停止します!
リンクは遅くて複雑です。多くの初心者はしばしばリンクプロセスの学習に苦労しており、安全でないコードを書くことに関しても最大の犯人です。これだけで、このアリーナアロケーターをヘッダーのみのライブラリにするのに十分な理由があります。私のコード(現在の状態)は非常に小さく、およそ300行です。一度#include箱から出し始めることができるのに、なぜこのような小さな実装を構築してリンクさせるのでしょうか?あなたが本当に問題を抱えている場合、シングルヘッダー形式のこのアロケーターは、あなたが望むなら、あなたがソース+ヘッダー構造に従うことを妨げません。ヘック、それをフォークしてソース+ヘッダーにしてください。それは理由でオープンソースです!
これはカーネルレベルのアロケーターを実装するのではなく、 mallocとfree (標準ライブラリまたはカスタム、選択)をラップします。
ソフトウェアはオープンソースであるべきだと思いますが、このライブラリを使用してオープンソースになるソフトウェアを要求することは倫理的ではないと思います。現代の技術と世界の現状では、記憶に安全なコードを書くことはこれまで以上に重要です。このため、このソフトウェアはApacheライセンスバージョン2.0の下でライセンスされています。条件に100 arena.h精通していると思わない限り、ソフトウェアの使用を検討している場合は、 LICENSE読むことを強くお勧めします。
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright 2024 Carter Dugan
Arena Allocatorのドキュメントはすべてarena.hにあります。ヘッダーファイルの上部に、便利なための使用のための簡単な手順を備えたコメントがあります。
1つの翻訳ユニットの1つのファイルの場合、次のものが必要です。
#define ARENA_IMPLEMENTATION
#include "arena.h"その時点から、他の翻訳ユニットの他のファイルは、通常#include "arena.h"通常#includeすることができます。定義/使用できる追加のマクロがあります。関数とマクロに関するセクションを参照してください。
arena.hには2つの構造体が定義されています。これは、それぞれとそのメンバーをリストします。
Arena_Allocationアリーナ割り当てのデータ構造。 ARENA_DEBUGが定義されている場合にのみ使用できます。
size_t index割り当ての開始が配置されているアリーナのインデックス。size_t sizeこの割り当てに割り当てられたメモリのサイズは、バイトの割り当て。char *pointer 。struct Arena_Allocation_s *nextリンクリストの次の割り当て。 Arenaのデータ構造。
char *region割り当てられたメモリの領域。size_t index次のポインターが分散するための地域のインデックス。size_t sizeバイトのアリーナに割り当てられたメモリのサイズ。unsigned long allocations行われたアリーナの割り当ての数。 ARENA_DEBUGが定義されている場合にのみ利用可能です。Arena_Allocation *head_allocationアリーナで行われた最初の割り当て(リンクリストに使用)。 ARENA_DEBUGが定義されている場合にのみ利用可能です。 /*
Allocate and return a pointer to memory to the arena
with a region with the specified size. Providing a
size of zero results in a failure.
Parameters:
size_t size | The size (in bytes) of the arena
memory region.
Return:
Pointer to arena on success, NULL on failure
*/
Arena * arena_create ( size_t size );
/*
Return a pointer to a portion of specified size of the
specified arena's region. Nothing will restrict you
from allocating more memory than you specified, so be
mindful of your memory (as you should anyways) or you
will get some hard-to-track bugs. By default, memory is
aligned by alignof(size_t), but you can change this by
#defining ARENA_DEFAULT_ALIGNMENT before #include'ing
arena.h. Providing a size of zero results in a failure.
Parameters:
Arena *arena | The arena of which the pointer
from the region will be
distributed
size_t size | The size (in bytes) of
allocated memory planned to be
used.
Return:
Pointer to arena region segment on success, NULL on
failure.
*/
ARENA_INLINE void * arena_alloc ( Arena * arena , size_t size );
/*
Same as arena_alloc, except you can specify a memory
alignment for allocations.
Return a pointer to a portion of specified size of the
specified arena's region. Nothing will restrict you
from allocating more memory than you specified, so be
mindful of your memory (as you should anyways) or you
will get some hard-to-track bugs. Providing a size of
zero results in a failure.
Parameters:
Arena *arena | The arena of which the pointer
from the region will be
distributed
size_t size | The size (in bytes) of
allocated memory planned to be
used.
unsigned int alignment | Alignment (in bytes) for each
memory allocation.
Return:
Pointer to arena region segment on success, NULL on
failure.
*/
void * arena_alloc_aligned ( Arena * arena , size_t size , unsigned int alignment );
/*
Copy the memory contents of one arena to another.
Parameters:
Arena *src | The arena being copied, the source.
Arena *dest | The arena being copied to. Must be created/allocated
already.
Return:
Number of bytes copied.
*/
ARENA_INLINE size_t arena_copy ( Arena * dest , Arena * src );
/*
Reset the pointer to the arena region to the beginning
of the allocation. Allows reuse of the memory without
realloc or frees.
Parameters:
Arena *arena | The arena to be cleared.
*/
ARENA_INLINE void arena_clear ( Arena * arena );
/*
Free the memory allocated for the entire arena region.
Parameters:
Arena *arena | The arena to be destroyed.
*/
ARENA_INLINE void arena_destroy ( Arena * arena );
/*
Returns a pointer to the allocation struct associated
with a pointer to a segment in the specified arena's
region.
Parameters:
Arena *arena | The arena whose region should
have a portion pointed to by
ptr.
void *ptr | The ptr being searched for
within the arena in order to
find an allocation struct
associated with it.
*/
Arena_Allocation * arena_get_allocation_struct ( Arena * arena , void * ptr );
/*
Adds an arena allocation to the arena's linked list of
allocations under debug.
Parameters:
Arena *arena | The arena whose allocation list
should be added to
size_t size | The size of the allocation being
added.
*/
void arena_add_allocation ( Arena * arena , size_t size );
/*
Deletes the arena's linked list of allocations under
debug.
Parameters:
Arena *arena | The arena whose allocation list
is being deleted.
*/
void arena_delete_allocation_list ( Arena * arena );コードでは、いくつかのオプションのマクロを定義できます。 ARENA_MALLOC 、 ARENA_FREE 、 ARENA_MEMCPY 、それぞれ代替malloc -like、 free -like、およびmemcpy -like関数に割り当てることができ、 arena.h標準的なライブラリ関数の代わりにそれらを使用します。 ARENA_DEBUG定義することにより、追加のデバッグ機能にアクセスするために、割り当てを追跡することができます。最後に、 ARENA_DEFAULT_ALIGNMENTの値を定義することにより、割り当てアライメントのデフォルト値を指定することもできます。例については、以下を参照してください。
// All of these are optional
// Replace standard library functions
#define ARENA_MALLOC <stdlib_malloc_like_allocator>
#define ARENA_FREE <stdlib_free_like_deallocator>
#define ARENA_MEMCPY <stdlib_memcpy_like_copier>
// for debug functionality:
#define ARENA_DEBUG
// If you would like to change the default alignment for
// allocations:
#define ARENA_DEFAULT_ALIGNMENT <alignment_value>また、タイプのアラインメントを決定するためのマクロもあります。他のすべてと同様に、C89フレンドリーでもありますが、C11の下でコンパイルすると、 stdalign.hのalignofが使用されます。
ARENA_ALIGNOF ( type ) // Gives alignment of `type` このコードは、C89標準をサポートし、任意のプラットフォームで実行する任意のコンパイラとともに構築するように書かれています。ただし、 Makefileを使用してWindowsに構築することにはいくつかの問題があります。以下のすべての情報をお読みください。
テストと例はコンパイルされ、次のコンパイラとバージョンの下で正常に実行されています。
テストと例がコンパイルされ、次のオペレーティングシステムで正常に実行されました。
MakeFileは現在、Valgrindの使用と.exe拡張機能の存在のために、 $ make test実行するときにWindowsで動作するように構成されていないことに注意してください。これは簡単な修正であり、私のTODOリストに載っているはずです(問題を開いて、これを自分で修正してください!)。
このプロジェクトには、貢献するための非常に簡単なガイドラインがあります。
arena.hのコードへの貢献については、機能要求を満たすかバグを修正するために問題に対処している場合にのみ、プルリクエストを開きます。コードスタイルに従って、プルリクエストを開く前に自動テストを実行します。すべてのテストに合格する必要があります。
機能のリクエストやバグについては、問題を開いてください。その後、この問題に自分で対処できます。
他のいずれかのために、問題を開き、それについて説明します。
arena.hの変更現時点では、コードスタイルのドキュメントはありませんが、ほとんどのことで既存のコードを読んで取り上げるのに十分なほど簡単である必要があります。問題が発生している場合は、FRの問題を自由に開いてください。すでに存在する場合は、あなたが混乱していることを説明することについてコメントしてください。
arena.hを変更する場合は、テストを実行する必要があります。次のセクションを参照してください。
arena.h内に機能を追加する場合は、 test.c内で適切なテストまたはテストを作成する必要があります。
arena.h内に機能を追加する場合は、 code_examples/に適切な例を作成し、 makefileに追加する必要がありますが、必須ではありません。
arena.h変更する場合は、 PRを開く前にテストを実行します。コードに変更を加えたPRを開くと、テストがすべて渡されない場合は、どのテストが間違っていると思われ、すべてのテストに合格することを妨げていることをPRにコメントしてください。テストが失敗し、PRに失敗したテストを修正すると主張するコメントがない場合、PRは無視されます。
バグと機能のリクエストに対処する以外に、 arena.h内の機能の機能要求またはバグの修正を満たすことは、 test.c内で関連するテストコードの変更または追加を許可します。コメントの形式でファイルの上部にあるtest.c内のテストコードのドキュメントがあります。
また、テストはValgrindリークフリーを通過する必要があり、 arena.h C89に準拠する必要があります。 Makefileを使用してこれを確認する必要がありますが、何らかの理由でできないか、したくない場合は、 test.cをコンパイルします。
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
コンプライアンスの場合は、 test_compliance.cをコンパイルします
-pedantic -std=c89 -Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
私が言ったように、あなたはMakefileでこれらすべてを行うことができます
$ make test
識別子
variable_nameです。ポインターの場合、アスタリスク( * )は、 type *variable_nameではなく変数名に添付する必要があります。type function_name(p1, p2, ...)など、小文字とヘビの場合である必要があります。ポインターの場合、アスタリスク( * )は、密度の型、たとえばtype* function_name(p1, p2, ...)型に取り付けられる必要があります。関数には、ファイルの上部の上にあるドキュメントのコメントのコメントを含むフォワード宣言が必要です。他の機能に対する順序が一貫していることを確認してください。struct StructNameなどのPascalケースである必要があります。それらはタイプフィードし、ヘッダーファイルの上部に配置する必要があります。ARENA_MACRO_NAME ARENA_ある必要があります。最初に私に相談せずにマクロを追加しないでください。ただし、既存のマクロを自由に変更してください。空白は、周囲の人々とコードの行の関連性に基づいています。これらのポイントの意味がわからない場合は、コードをご覧ください。次のようにフォーマットする必要があります。
可能な限りエラーチェックを行い、ポインターを返す関数のエラーでNULLを返すなど、標準のライブラリ実装の動作を模倣したり、整数関数から整数エラー値を返します。早期エラーチェックを使用する必要があります。つまり、エラーが生成されたらすぐにチェックすることを意味します。失敗したmallocコールの後にNULLの確認が返されました。
コメントは、あなたがしたことではなく、あなたが何かをした理由を説明する必要があります。言い換えれば、コードは自明である必要があります。コメントの形式の関数のドキュメントは、次の形式で関数の上に配置する必要があります。
/*
Description of function, description of function description of function.
Description of function description of function, description of function
description of function.
Parameters:
paramter1_type paramter1_name | Description of parameter 1, description
of parameter one description of paramter
1.
paramter2_type paramter2_name | Description of parameter 2, description
of parameter one description of paramter
2.
Return:
Description of return value, description of return value description of return value.
*/