단일 헤더 아레나 할당 자. C89 호환.
arena.h 에 대한 수정. h Arena 할당자는 여러 할당을 그룹으로 해제 할 수 있도록하여 쉽고 빠르며 안전한 동적 메모리 관리를 달성 할 수있는 간단한 방법입니다. 이것은 넓은 영역에 메모리를 할당 한 다음 필요에 따라 해당 메모리의 일부를 분배하여 malloc 호출의 양을 줄임으로써 수행됩니다 (간단한 포인터 산술에 비해 느리게).
경기장을 파괴하면 해방과 모든 내용물을 자유롭게하여 느린 free 통화의 양을 줄입니다. 더 나아가서, 당신은 단순히 메모리 포인터를 0 으로 재설정함으로써 경기장을 지우면서 그것을 재사용하고 더 많은 malloc 과 free 의 필요성을 제거 할 수 있습니다.
이 환상적인 기사를 읽음으로써 Arena/Zone/Region 할당 자에 대한 자세한 내용을 알 수 있습니다.
나는 이것을 짧게 유지할 것이다. 나는 그것을 사용하기 때문이 아니라 재미에 대한 C89 준수를 유지하고 있습니다. 나는 개인적으로 C11 즐거움입니다. C89가 유일한 방법이라고 생각한다면, 당신에게 좋습니다! 하지만 당신은 틀 렸습니다.
이 프로젝트를 다른 프로그래머와 공유 할 때마다, 내가받는 가장 일반적인 응답 중 하나는 다음과 같습니다. 구현/로직 코드를 헤더 파일에 넣지 않아야합니다! 나는이 진술에 세 가지 이유로 문제를 일으킨다 ...
그것은 구식과 결과적으로 해당 구성이 일반적으로 도입되는 교육 시스템에서 유해한 구성이 여전히 시행되고 있음을 보여줍니다.
이 진술을하는 사람은 그것을 믿는 실제 이유가 거의 없습니다. 이 사람은 왜 "구현/로직 코드를 헤더 파일에 넣지 말아야하는지"왜 생각해 보입니까? 그들이 동의하기로 선택한 이유 에 대한 근거없이 그들이 들었던 것을 단순히 역류하는 것은 어떤 식 으로든 나를 도울 수 없으며,이 사람은 내가 한 것처럼 그것을 받아들이기를 기대해서는 안됩니다.
헤더 전용/단일 헤더 라이브러리에 대한 가장 크고 가장 유효한 비판은 헤더로 변경하려면 모든 파일을 포함하는 모든 파일을 다시 컴파일해야한다는 것입니다. 내 프로젝트의 경우 arena.h 를 변경하는 경우 실제 구현이 #define 의 ARENA_IMPLEMENTATION Macro의 번역 장치에만 포함 되더라도이를 포함하는 모든 파일이 재건 될 수 있습니다. 솔루션? arena.h 원하는 상태에 있으면 변경을 중지하십시오!
연결은 느리고 복잡합니다. 많은 초보자들은 종종 링크 프로세스를 배우는 데 어려움을 겪고 있으며 안전하지 않은 코드를 작성할 때 가장 큰 범인입니다. 이것 만으로도이 경기장 할당을 헤더 전용 라이브러리로 만들 수있는 충분한 이유입니다. 내 코드 (현재 상태)는 매우 작고 대략 300 줄입니다. 단순히 #include 를 한 번 #색상으로 사용하고 상자에서 사용할 수있을 때 그런 작은 구현을 빌드하고 연결하게하는 이유는 무엇입니까? 실제로 문제가있는 경우, 단일 헤더 형식 의이 할당자를 사용하면 원하는 경우 소스+헤더 구조를 따르는 것을 방해하지 않습니다. 도대체, 자유롭게 그것을 포크하고 소스+헤더로 만들어주십시오. 이유가있는 오픈 소스입니다!
이것은 커널 수준 할당자를 구현하지 않고 대신 malloc 과 free (표준 라이브러리 또는 사용자 정의, 선택)를 랩핑합니다.
소프트웨어가 오픈 소스 여야한다고 생각하지만이 라이브러리를 사용하는 소프트웨어를 요구하는 것은 윤리적이라고 생각하지 않습니다. 현대 기술과 세계의 현재 상태에서 메모리-안전 코드를 작성하는 것이 그 어느 때보 다 중요합니다. 이러한 이유로이 소프트웨어는 Apache 라이센스 버전 2.0에 따라 라이센스가 부여됩니다. 이용 약관에 100% 익숙하다고 생각하지 않는 한 소프트웨어 사용을 고려하고있는 경우 LICENSE (아래 포함, arena.h 및 자체 파일)를 읽는 것이 좋습니다.
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 에서 찾을 수 있습니다. 헤더 파일 상단에는 편의를 위해 사용을위한 빠른 지침이있는 주석이 있습니다.
하나의 번역 장치에있는 하나의 파일 의 경우 다음이 필요합니다.
#define ARENA_IMPLEMENTATION
#include "arena.h" 이 시점부터 다른 번역 단위의 다른 파일은 단순히 #include "arena.h" 정상적으로 포함시킬 수 있습니다. 정의/사용할 수있는 추가 매크로가 있습니다. 함수 및 매크로에 관한 섹션을 참조하십시오.
arena.h 에는 정의 된 두 개의 struct가 있습니다. 여기에는 각자와 함께 회원이 나와 있습니다.
Arena_Allocation Arena 할당의 데이터 구조. 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에서 첫 번째 할당 (링크 된 목록에 사용). 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 functions에 할당 될 수 있으며 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를 구축하는 데 몇 가지 문제가 있습니다. 아래 정보를 모두 읽으십시오.
테스트 및 예제는 다음 컴파일러 및 버전에서 컴파일되어 성공적으로 실행되었습니다.
테스트 및 예제는 다음과 같은 운영 체제에서 컴파일되어 성공적으로 실행되었습니다.
Valgrind의 사용 및 .exe 확장자가 없기 때문에 $ make test 실행할 때 Windows에서 작동하도록 현재 MakeFile이 현재 Windows 에서 작동하도록 구성되지 않았습니다. 이것은 간단한 수정이어야하며 내 할 일 목록에 있습니다 (문제를 열고 직접 해결하십시오!).
이 프로젝트에는 기여를위한 매우 간단한 지침이 있습니다.
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 내에서 관련 테스트 코드를 수정하거나 추가 할 수 있으며 PR을 승인하려면 그렇게해야합니다. 댓글 형식으로 파일의 맨 위에 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 이어야합니다. 그것들은 타이핑하고 헤더 파일의 상단 주위에 위치해야합니다.ARENA_ , 예를 들어 ARENA_MACRO_NAME 시작으로 모든 캡과 스나 케이스 여야합니다. 먼저 상담하지 않고 매크로를 추가하지 마십시오 . 그러나 기존 매크로를 자유롭게 변경하십시오.공백은 코드 라인과 주변의 코드 라인의 관련성을 기반으로합니다. 이 점이 무엇을 의미하는지 이해하지 못하면 코드를보십시오. 다음과 같이 형식화되어야합니다.
오류 검사는 가능할 때마다 수행해야하며 포인터를 반환하는 기능의 오류 또는 정수 함수에서 정수 오류 값을 반환하는 기능에서 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.
*/