Asignador de arena de un solo cabezazo. C89 compatible.
arena.h Los asignadores de arena son una forma simple de lograr una gestión de memoria dinámica más fácil, más rápida y segura al permitir que múltiples asignaciones se liberen como grupo. Esto se realiza asignando la memoria en grandes regiones y luego distribuyendo porciones de esa memoria según sea necesario, reduciendo la cantidad de llamadas malloc (que son lentas en comparación con la aritmética del puntero simple).
Cuando destruyes la arena, también lo liberas y todo su contenido, reduciendo la cantidad de llamadas free que también son lentas. Yendo más allá, puede borrar las arenas simplemente restableciendo sus punteros de memoria a 0 , lo que le permite reutilizarlos y eliminando la necesidad de aún más malloc y los free .
Puede obtener más información sobre los asignadores de arena/zona/región leyendo este fantástico artículo.
Mantendré esto corto. Mantengo el cumplimiento de C89 por diversión, no porque lo use. Personalmente soy un disfrute C11. Si crees que C89 es la única forma, bueno, ¡bien para ti! Pero te equivocas.
Cada vez que comparto este proyecto con otros programadores, una de las respuestas más comunes que recibo es algo así: ¡nunca debe poner el código de implementación/lógica en un archivo de encabezado! Estoy en desacuerdo con esta declaración por tres razones ...
Muestra que una construcción nociva y, por consecuencia, todavía se está aplicando en el sistema educativo, que es donde generalmente se introduce dicha construcción.
Muy raramente la persona que hace esta declaración tiene una razón real para creerla. ¿Esta persona alguna vez piensa por qué debería "nunca poner el código de implementación/lógica en un archivo de encabezado"? Simplemente regurgitar lo que han escuchado sin ninguna base de por qué eligieron estar de acuerdo con él no me ayuda de ninguna manera, y esta persona no debería esperar que lo acepte como lo ha hecho.
La crítica más grande y válida de las bibliotecas de encabezado/liderazgo único es que un cambio en el encabezado requiere una re-compilación de todos los archivos que lo incluyen. En el caso de mi proyecto, hacer cambios en arena.h , a pesar de que la implementación real solo está contenida en la unidad de traducción que #define es la macro ARENA_IMPLEMENTATION , dará como resultado la reconstrucción de todos los archivos que lo incluyen. La solución? Una vez que arena.h está en el estado deseado, ¡deje de hacer cambios!
El enlace es lento y complicado. Muchos principiantes, a menudo, luchan por aprender el proceso de vinculación, y también son el mayor culpable cuando se trata de escribir código inseguro. Esta por sí sola es una razón suficiente para que haga este asignador de arena una biblioteca solo de encabezado. Mi código (en su estado actual) es muy pequeño, aproximadamente 300 líneas. ¿Por qué te haría construir y vincular una implementación tan pequeña cuando simplemente pudieras #include una vez y comenzar a usarla fuera de la caja? Si realmente tiene un problema con él, este asignador en el formato de un solo cabezal no le impide seguir la construcción de fuente+encabezado si así lo desea. Diablos, siéntete libre de desembolsarlo y hacerlo fuente+encabezado, ¡es código abierto por una razón!
Esto no implementa un asignador de nivel de núcleo, sino que envuelve malloc y free (biblioteca estándar o personalizado, su elección).
Si bien creo que el software debería ser de código abierto, no creo que sea ético requerir un software que use esta biblioteca para que también sea de código abierto. En la era moderna de la tecnología y el estado actual del mundo, escribir código seguro de memoria es más importante que nunca. Por esta razón, este software tiene licencia bajo la Licencia Apache versión 2.0. Se le recomienda encarecidamente que lea la LICENSE (incluida a continuación, en arena.h , y su propio archivo en este repositorio) si está considerando usar el software, a menos que crea que está 100% familiarizado con los términos y condiciones.
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 documentación para el asignador de arena se puede encontrar en arena.h . Hay un comentario en la parte superior del archivo de encabezado con instrucciones rápidas de uso para su conveniencia.
Para un archivo en una unidad de traducción , necesita lo siguiente:
#define ARENA_IMPLEMENTATION
#include "arena.h" A partir de ese momento, otros archivos en otras unidades de traducción pueden simplemente #include "arena.h" normalmente. Hay macros adicionales que puede definir/usar. Consulte la sección sobre funciones y macros.
Hay dos estructuras definidas en arena.h . Esto enumera cada uno junto con sus miembros.
Arena_Allocation La estructura de datos para una asignación de arena. Disponible solo cuando se define ARENA_DEBUG .
size_t index El índice en la arena en la que se encuentra el comienzo de la asignación.size_t size El tamaño de la memoria asignada a esta asignación en bytes.char *pointer El puntero asociado para la asignación.struct Arena_Allocation_s *next la siguiente asignación en la lista vinculada. Arena la estructura de datos para una arena.
char *region La región de la memoria asignada.size_t index El índice de la región para el siguiente puntero que se distribuirá.size_t size El tamaño de la memoria asignada a la arena en bytes.unsigned long allocations el número de asignaciones de arena que se han realizado. Solo disponible cuando se define ARENA_DEBUG .Arena_Allocation *head_allocation La primera asignación realizada en la arena (utilizada para una lista vinculada). Solo disponible cuando se define 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 ); En su código, puede definir algunas macros opcionales. ARENA_MALLOC , ARENA_FREE y ARENA_MEMCPY se pueden asignar a funciones alternativas malloc -Like, free -Like -Like y memcpy , respectivamente, y arena.h los usará en lugar de funciones de biblioteca estándar. Puede acceder a la funcionalidad de depuración adicional para realizar un seguimiento de las asignaciones definiendo ARENA_DEBUG . Finalmente, también puede especificar un valor predeterminado para la alineación de asignación definiendo un valor para ARENA_DEFAULT_ALIGNMENT . Vea a continuación los ejemplos.
// 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> También hay una macro para determinar la alineación de los tipos. Como todo lo demás, también es amigable con C89, aunque al compilar bajo C11 usará stdalign.h 's alignof .
ARENA_ALIGNOF ( type ) // Gives alignment of `type` El código fue escrito para construir con cualquier compilador que admita el estándar C89 y se ejecute en cualquier plataforma. Sin embargo, hay algunos problemas con la construcción en Windows con The Makefile . Lea toda la información a continuación.
Las pruebas y ejemplos se han compilado y ejecutado con éxito bajo los siguientes compiladores y versiones:
Las pruebas y ejemplos se compilaron y se ejecutaron con éxito en los siguientes sistemas operativos:
Tenga en cuenta que el makfile actualmente no se ha configurado para funcionar en Windows cuando se ejecuta $ make test debido al uso de Valgrind y el ausente de extensiones .exe . Esta debería ser una solución simple y está en mi lista de TODO (¡no dude en abrir un problema y solucionarlo usted mismo!).
Este proyecto tiene pautas muy simples para contribuir.
Para cualquier contribución al código de arena.h , abra una solicitud de extracción solo si está abordando un problema para cumplir con una solicitud de función o solucionar un error . Siga el estilo del código y ejecute las pruebas automatizadas antes de abrir una solicitud de extracción. Todas las pruebas deben pasarse.
Para solicitudes de funciones o errores , abra un problema . Luego puede abordar este problema usted mismo.
Para cualquier otra cosa , abra un problema y lo discutiremos.
arena.hPor el momento, no hay documentación para el estilo del código, pero debería ser lo suficientemente simple como para retomar la lectura del código existente para la mayoría de las cosas. Si tiene problemas, no dude en abrir un problema para un FR. Si ya existe, comente sobre él describiendo lo que está confundido.
Si modifica arena.h en absoluto, debe ejecutar las pruebas. Ver la siguiente sección.
Si agrega una función dentro de arena.h , debe crear una prueba o pruebas adecuadas dentro de test.c
Si agrega una función dentro de arena.h , debe tener un ejemplo adecuado en code_examples/ y agregarla al makefile , pero no es necesario.
Si cambia arena.h en absoluto, ejecute las pruebas antes de abrir un PR . Si abre un PR con modificaciones al código y las pruebas no pasan todas, haga un comentario sobre su PR que indica qué prueba cree que está mal y le impide pasar todas las pruebas. Si alguna prueba falla y su PR no tiene un comentario que afirme corregir una prueba fallida, su PR será ignorado cerrado.
Fuera de abordar los errores y las solicitudes de funciones, cumpliendo una solicitud de función o una corrección de errores para la funcionalidad dentro de arena.h permite modificar o agregar código de prueba relevante dentro de test.c , y debe hacerlo si desea que su PR sea reconocido. Hay documentación para el código de prueba dentro de test.c en la parte superior del archivo en forma de comentarios.
Las pruebas también deben pasar a través de Valgrind sin fugas, y arena.h debe cumplir con C89. Debe verificar esto usando el Makefile , pero si por alguna razón no puede o no quiere, compile test.c con
-Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
Y para el cumplimiento, compile test_compliance.c con
-pedantic -std=c89 -Werror -Wall -Wextra -Wstrict-prototypes -Wold-style-definition -Wmissing-prototypes -Wmissing-declarations -Wdeclaration-after-statement
Como dije, puedes hacer todo esto con The Makefile
$ make test
Identificadores
variable_name . Para los punteros , el asterisco ( * ) debe adjuntar al nombre de la variable, no al tipo, por ejemplo, type *variable_name .type function_name(p1, p2, ...) . En el caso de los punteros, el asterisco ( * ) debe conectarse al tipo de densidad, por ejemplo, type* function_name(p1, p2, ...) . Las funciones deben tener una declaración a plazo con un comentario para la documentación sobre él alrededor de la parte superior del archivo, asegúrese de que el pedido en relación con otras funciones sea consistente.struct StructName . Deben ser typedef'd y ubicados alrededor de la parte superior del archivo de encabezado.ARENA_ , por ejemplo, ARENA_MACRO_NAME . Evite agregar macros sin consultarme primero . Sin embargo, siéntase libre de hacer cambios en las macros existentes.El espacio en blanco se basa en la relevancia de una línea de código para quienes lo rodean. Si no entiende lo que significan estos puntos, mire el código. Debe formatearse de la siguiente manera:
La comprobación de errores debe hacerse siempre que sea posible e imite el comportamiento de las implementaciones de la biblioteca estándar, como devolver el error NULL en las funciones que devuelven punteros o devolviendo los valores de error entero de las funciones enteras. Debe usar la verificación de errores temprano , lo que significa verificar errores tan pronto como puedan producirse, por ejemplo. Verificar un NULL regresó después de una llamada fallida malloc .
Los comentarios deberían describir por qué hiciste algo, no lo que hiciste. En otras palabras, su código debe explicarse por sí mismo. La documentación de las funciones en forma de comentarios debe ubicarse sobre la función en el siguiente formato:
/*
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.
*/