Allocator de l'arène à tête. C89 compatible.
arena.h Les allocateurs Arena sont un moyen simple de réaliser la gestion de la mémoire dynamique plus facile, plus rapide et plus sûre en permettant à plusieurs allocations d'être libérées en groupe. Cela se fait en allouant la mémoire dans de grandes régions, puis en distribuant des parties de cette mémoire au besoin, en réduisant la quantité d'appels malloc (qui sont lents par rapport à l'arithmétique du pointeur simple).
Lorsque vous détruisez l'arène, vous le libérez également et tout son contenu, réduisant la quantité d'appels free qui sont également lents. En allant plus loin, vous pouvez effacer les arènes en réinitialisant simplement leurs pointeurs de mémoire vers 0 , vous permettant de les réutiliser et d'éliminer le besoin de plus de malloc et de free .
Vous pouvez en savoir plus sur les allocateurs Arena / Zone / Region en lisant cet article fantastique.
Je vais garder cela court. Je maintiens la conformité C89 pour le plaisir, pas parce que je l'utilise. Personnellement, je suis un plaisir C11. Si vous pensez que C89 est le seul moyen, eh bien, bon pour vous! Mais vous vous trompez.
Chaque fois que je partage ce projet avec d'autres programmeurs, l'une des réponses les plus courantes que je reçois est quelque chose dans le sens de: vous ne devez jamais mettre du code d'implémentation / logique dans un fichier d'en-tête! Je conteste cette déclaration pour trois raisons ...
Il montre qu'une construction obsolète et, par conséquent, est toujours appliquée dans le système éducatif, où ladite construction est généralement introduite.
Très rarement, la personne qui fait cette déclaration a une raison réelle de le croire. Cette personne pense-t-elle jamais à la raison pour laquelle elle devrait "ne jamais mettre le code d'implémentation / logique dans un fichier d'en-tête"? Le simple fait de régurgiter ce qu'ils ont entendu sans aucune base pour savoir pourquoi ils ont choisi de s'entendre avec cela ne m'aide en aucune façon, et cette personne ne devrait pas s'attendre à ce que je l'accepte simplement comme ils l'ont fait.
La critique la plus importante et la plus valable des bibliothèques d'en-tête uniquement / à tête est qu'un changement à l'en-tête nécessite la recompilation de tous les fichiers qui l'incluent. Dans le cas de mon projet, apporter des modifications à arena.h , même si la mise en œuvre réelle n'est contenue que dans l'unité de traduction que la macro ARENA_IMPLEMENTATION #define entraînera la reconstruction de tous les fichiers qui l'incluent. La solution? Une fois arena.h est dans l'état souhaité, arrêtez d'apporter des modifications!
La liaison est lente et compliquée. De nombreux débutants ont souvent du mal à apprendre le processus de liaison, et ils sont également le plus grand coupable lorsqu'il s'agit d'écrire du code dangereux. Cela seul est une raison suffisante pour moi de faire de cette arène une bibliothèque d'en-tête uniquement. Mon code (dans son état actuel) est très petit, environ 300 lignes. Pourquoi est-ce que je vous ferais créer et lier une si petite implémentation alors que vous pourriez simplement l' #include une fois et commencer à l'utiliser hors de la boîte? Si vous avez vraiment un problème avec cela, cet allocateur au format à un seul tête ne vous empêche pas de suivre la construction de la source + de l'en-tête si vous le souhaitez. Heck, n'hésitez pas à le fourrer et à le faire source + en-tête, c'est open source pour une raison!
Cela n'implémente pas un allocateur au niveau du noyau, mais enveloppe plutôt malloc et free (bibliothèque standard ou personnalité, votre choix).
Bien que je pense que les logiciels devraient être open source, je ne pense pas qu'il serait éthique d'exiger un logiciel qui utilise cette bibliothèque pour être également open source. À l'ère moderne de la technologie et de l'état actuel du monde, l'écriture de code sécurisé par la mémoire est plus importante que jamais. Pour cette raison, ce logiciel est sous licence en vertu de la version 2.0 de la licence Apache. Vous êtes fortement encouragé à lire la LICENSE (incluse ci-dessous, dans arena.h , et son propre fichier dans ce référentiel) si vous envisagez d'utiliser le logiciel, sauf si vous croyez que vous connaissez à 100% les termes et conditions.
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
La documentation de l'allocateur de l'arène peut toutes être trouvées dans arena.h . Il y a un commentaire en haut du fichier d'en-tête avec des instructions rapides d'utilisation pour votre commodité.
Pour un fichier dans une unité de traduction , vous avez besoin de ce qui suit:
#define ARENA_IMPLEMENTATION
#include "arena.h" À partir de ce moment, d'autres fichiers d'autres unités de traduction peuvent simplement #include "arena.h" normalement. Il existe des macros supplémentaires que vous pouvez définir / utiliser. Voir la section sur les fonctions et les macros.
Il y a deux structures définies dans arena.h . Cela répertorie chacun avec ses membres.
Arena_Allocation La structure de données pour une allocation de l'arène. Disponible uniquement lorsque ARENA_DEBUG est défini.
size_t index L'index dans l'arène dans lequel se trouve le début de l'allocation.size_t size La taille de la mémoire allouée à cette allocation en octets.char *pointer le pointeur associé à l'allocation.struct Arena_Allocation_s *next l'allocation suivante dans la liste liée. Arena La structure de données pour une arène.
char *region La région de la mémoire allouée.size_t index L'indice de la région pour le pointeur suivant à distribution.size_t size La taille de la mémoire allouée à l'arène en octets.unsigned long allocations le nombre d'allocations d'arènes qui ont été faites. Uniquement disponible lorsque ARENA_DEBUG est défini.Arena_Allocation *head_allocation La première allocation réalisée dans l'arène (utilisée pour une liste liée). Uniquement disponible lorsque ARENA_DEBUG est défini. /*
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 ); Dans votre code, vous pouvez définir certaines macros en option. ARENA_MALLOC , ARENA_FREE et ARENA_MEMCPY peuvent être affectées à des fonctions alternatives respectivement malloc , de type free et memcpy , et arena.h les utilisera à la place des fonctions de bibliothèque standard. Vous pouvez accéder à des fonctionnalités de débogage supplémentaires pour garder une trace des allocations en définissant ARENA_DEBUG . Enfin, vous pouvez également spécifier une valeur par défaut pour l'alignement d'allocation en définissant une valeur pour ARENA_DEFAULT_ALIGNMENT . Voir ci-dessous pour des exemples.
// 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> Il existe également une macro pour déterminer l'alignement des types. Comme tout le reste, il est également adapté à C89, bien que lors de la compilation sous C11, il utilisera alignof de stdalign.h .
ARENA_ALIGNOF ( type ) // Gives alignment of `type` Le code a été écrit pour construire avec tout compilateur qui prend en charge la norme C89 et exécuté sur n'importe quelle plate-forme. Cependant, il y a des problèmes avec la construction de Windows avec le Makefile . Veuillez lire toutes les informations ci-dessous.
Les tests et les exemples ont été compilés et exécutés avec succès sous les compilateurs et versions suivants:
Les tests et les exemples ont été compilés et exécutés avec succès sur les systèmes d'exploitation suivants:
Remarque Le MakeFile n'a actuellement pas été configuré pour fonctionner sur Windows lors de l'exécution $ make test en raison de l'utilisation de Valgrind et de l'absence des extensions .exe . Cela devrait être une solution simple et figure sur ma liste de tâches (n'hésitez pas à ouvrir un problème et à résoudre ce problème vous-même!).
Ce projet a des directives très simples pour la contribution.
Pour toute contribution au code d' arena.h , veuillez ouvrir une demande de traction uniquement si vous résolvez un problème pour répondre à une demande de fonctionnalité ou corriger un bogue . Suivez le style de code et exécutez les tests automatisés avant d'ouvrir une demande de traction. Tous les tests doivent être passés.
Pour les demandes de fonctionnalités ou les bogues , veuillez ouvrir un problème . Vous pouvez ensuite résoudre ce problème vous-même.
Pour tout autre chose , ouvrez un problème et nous en discuterons.
arena.hPour le moment, il n'y a pas de documentation pour le style de code, mais il devrait être assez simple à reprendre en lisant le code existant pour la plupart des choses. Si vous avez des problèmes, n'hésitez pas à ouvrir un problème à un FR. S'il existe déjà, commentez-le en décrivant ce que vous êtes confus.
Si vous modifiez arena.h , vous devez exécuter les tests. Voir la section suivante.
Si vous ajoutez une fonctionnalité dans arena.h , vous devez créer un test ou des tests adéquats dans test.c
Si vous ajoutez une fonctionnalité dans arena.h , vous devez un exemple adéquat dans code_examples/ et l'ajouter à la makefile , mais il n'est pas requis.
Si vous modifiez arena.h , exécutez les tests avant d'ouvrir un PR . Si vous ouvrez un PR avec des modifications du code et que les tests ne passent pas tous, faites un commentaire sur votre RP indiquant quel test vous croyez être faux et vous empêche de passer tous les tests. Si un test échoue et que votre PR n'a pas de commentaire qui prétend corriger un test échoué, votre RP sera ignoré.
En dehors de l'adresser des bogues et des demandes de fonctionnalités, la réalisation d'une demande de fonctionnalité ou d'une correction de bogue pour les fonctionnalités dans arena.h permet de modifier ou d'ajouter le code de test pertinent dans test.c , et vous devez le faire si vous souhaitez que votre PR soit reconnu. Il existe une documentation pour tester le code dans test.c en haut du fichier sous forme de commentaires.
Les tests doivent également passer par Valgrind sans fuite et arena.h doit être conforme au C89. Vous devriez vérifier cela en utilisant le Makefile , mais si pour une raison quelconque, vous ne pouvez pas ou ne le souhaitez pas, compiler test.c avec
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
Et pour la conformité, compilent test_compliance.c avec
-pedantic -std=c89 -Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
Comme je l'ai dit, vous pouvez faire tout cela avec le Makefile
$ make test
Identificateurs
variable_name . Pour les pointeurs , l'astérisque ( * ) doit être attaché au nom de la variable, pas au type, par exemple type *variable_name .type function_name(p1, p2, ...) . Dans le cas des pointeurs, l'astérisque ( * ) doit être attaché au type de densité, par exemple type* function_name(p1, p2, ...) . Les fonctions doivent avoir une déclaration avant avec un commentaire pour la documentation supérieure à celle-ci autour du haut du fichier, assurez-vous que l'ordre par rapport aux autres fonctions est cohérent.struct StructName . Ils doivent être typés et situés autour du haut du fichier d'en-tête.ARENA_ , par exemple ARENA_MACRO_NAME . Veuillez éviter d'ajouter des macros sans me consulter en premier . N'hésitez pas à apporter des modifications aux macros existantes.L'espace blanc est basé sur la pertinence d'une ligne de code pour ceux qui l'entourent. Si vous ne comprenez pas ce que ces points signifient, veuillez consulter le code. Il doit être formaté comme suit:
La vérification des erreurs doit être effectuée chaque fois que possible et imiter le comportement des implémentations de bibliothèque standard, telles que le renvoi NULL sur l'erreur dans les fonctions qui renvoient les pointeurs ou le renvoi des valeurs d'erreur entière à partir des fonctions entières. Vous devez utiliser la vérification des erreurs précoces , ce qui signifie vérifier les erreurs dès qu'ils pourraient être produits, par exemple. Vérification d'un NULL est retourné après un appel malloc défaillant.
Les commentaires devraient décrire pourquoi vous avez fait quelque chose, pas ce que vous avez fait. En d'autres termes, votre code devrait être explicite. La documentation des fonctions sous forme de commentaires doit être située au-dessus de la fonction dans le format suivant:
/*
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.
*/