├── LICENSE ├── Makefile ├── README.md ├── example.c ├── inc ├── dalloc.h ├── dalloc_conf.h └── dalloc_types.h └── src └── dalloc.c /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Alexey Vasilenko 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | CC := gcc 2 | INCLUDES := -Iinc 3 | SOURCES = $(wildcard src/*.c) 4 | SOURCES += $(wildcard *.c) 5 | OBJECTS := $(patsubst %.c,%.o,${SOURCES}) 6 | TARGET := example 7 | FLAGS := -lc 8 | 9 | $(TARGET): $(OBJECTS) 10 | $(CC) $(OBJECTS) $(INCLUDES) $(FLAGS) -o $(TARGET) 11 | rm -f *.o 12 | rm -f src/*.o 13 | 14 | %.o: %.c 15 | $(CC) -c $(INCLUDES) $< -o $@ 16 | 17 | clean: 18 | rm -f *.o 19 | rm -f ${TARGET} 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # About the project 2 | This is the custom implementation of function malloc for embedded systems, that defragmentate memory after using it. Good solution when you need to allocate memory dynamically, but memory fragmentation is the problem. On this allocator based such project as [uvector](https://github.com/SkyEng1neering/uvector), [ustring](https://github.com/SkyEng1neering/ustring) and [usmartpointer](https://github.com/SkyEng1neering/usmartpointer). 3 | 4 | ## What is the problem that [dalloc](https://github.com/SkyEng1neering/dalloc) solves? 5 | ### Here is an illustration of memory fragmentation problem, while using default malloc function: 6 | ![this](https://github.com/SkyEng1neering/files/blob/main/default_malloc.drawio%20(1).png) 7 | On the last step there are 7 kB of free memory but not in solid region, so allocating of 4 kB fails 8 |

9 | 10 | ### And how dalloc works: 11 | ![this](https://github.com/SkyEng1neering/files/blob/main/defrag_malloc.drawio.png) 12 | 13 | ## How it works 14 | When you call allocate function, it saves the pointer to the pointer of allocated memory area and when corresponding memory region is freed - the defragmentation procedure executes, an the content of pointer to the memory area is replaced by new actual value. So using of dalloc allocator is not the same as default malloc. 15 | 16 | # Usage 17 | ## Simple examples of using dalloc 18 | In your project you can use only one heap area, and several heap areas as well. 19 | If you want to use only one heap memory area in your project, you can do it like this: 20 | ```c++ 21 | /* File dalloc_conf.h */ 22 | #define USE_SINGLE_HEAP_MEMORY 23 | #define SINGLE_HEAP_SIZE 4096UL //define heap size that you want to have 24 | ``` 25 | 26 | ```c++ 27 | #include "dalloc.h" 28 | 29 | int main(){ 30 | /* Allocate memory region in heap memory */ 31 | uint8_t *data_ptr = NULL; 32 | uint32_t allocation_size = 8; 33 | def_dalloc(allocation_size, (void**)&data_ptr); 34 | 35 | /* Check if allocation is successful */ 36 | if(data_ptr == NULL){ 37 | printf("Can't allocate %u bytes\n", allocation_size); 38 | return 0; 39 | } 40 | 41 | /* Now you can use allocated memory */ 42 | for(uint32_t i = 0; i < allocation_size; i++){ 43 | data_ptr[i] = 0xDE; 44 | } 45 | 46 | /* Free allocated memory */ 47 | def_dfree((void**)&data_ptr); 48 | 49 | return 0; 50 | } 51 | 52 | ``` 53 | 54 | If you want to use several different heap areas, you can define it explicitly: 55 | 56 | ```c++ 57 | /* File dalloc_conf.h */ 58 | //#define USE_SINGLE_HEAP_MEMORY 59 | ``` 60 | 61 | ```c++ 62 | #include "dalloc.h" 63 | 64 | #define HEAP_SIZE 32 65 | 66 | /* Declare an array that will be used for dynamic memory allocations */ 67 | uint8_t heap_array[HEAP_SIZE]; 68 | 69 | /* Declare an dalloc heap structure, it contains all allocations info */ 70 | heap_t heap; 71 | 72 | int main(){ 73 | /* Init heap memory */ 74 | heap_init(&heap, (void*)heap_array, HEAP_SIZE); 75 | 76 | /* Allocate memory region in heap memory */ 77 | uint8_t *data_ptr = NULL; 78 | uint32_t allocation_size = 8; 79 | dalloc(&heap, allocation_size, (void**)&data_ptr); 80 | 81 | /* Check if allocation is successful */ 82 | if(data_ptr == NULL){ 83 | printf("Can't allocate %u bytes\n", allocation_size); 84 | return 0; 85 | } 86 | 87 | /* Now you can use allocated memory */ 88 | for(uint32_t i = 0; i < allocation_size; i++){ 89 | data_ptr[i] = 0xDE; 90 | } 91 | 92 | /* Free allocated memory */ 93 | dfree(&heap, (void**)&data_ptr, USING_PTR_ADDRESS); 94 | 95 | return 0; 96 | } 97 | 98 | ``` 99 | ## Limitations 100 | As the address of pointer variable being saved and the value of the pointer variable is being updated when defragmentation is running - the pointer that was passed to **dalloc** function must exist before dfree function call, so you **can't** do something like this: 101 | 102 | ```c++ 103 | uint8_t* func_that_use_dalloc(heap_t *heap_ptr, uint32_t some_data_len){ 104 | uint8_t* data_ptr = NULL; 105 | dalloc(heap, some_data_len, (void**)&data_ptr); 106 | return data_ptr; 107 | } 108 | ``` 109 | Because when you call this function - the memory is allocated, but after this the pointer variable **data_ptr** which address that saves in heap_t structure isn't exist. So when you call **dfree** function, when defragmentation start you can get hard fault exception. 110 | 111 | So the pointer which contains allocated memory address should exist in memory after allocating procedure. You can do this for example: 112 | 113 | ```c++ 114 | uint8_t* data_ptr = NULL;//data_ptr is just global variable 115 | 116 | bool func_that_use_dalloc(heap_t *heap_ptr, uint32_t some_data_len){ 117 | dalloc(heap, some_data_len, (void**)&data_ptr); 118 | 119 | /* Check if allocation is successful */ 120 | if(data_ptr == NULL){ 121 | return false; 122 | } 123 | return true; 124 | } 125 | ``` 126 | 127 | Or this: 128 | 129 | ```c++ 130 | uint8_t* data_ptr = NULL;//data_ptr is the variable somewhere in your code 131 | 132 | bool func_that_use_dalloc(heap_t *heap_ptr, uint8_t** data_ptr_address, uint32_t some_data_len){ 133 | dalloc(heap, some_data_len, (void**)data_ptr_address); 134 | 135 | /* Check if allocation is successful */ 136 | if(*data_ptr_address == NULL){ 137 | return false; 138 | } 139 | return true; 140 | } 141 | 142 | func_that_use_dalloc(&heap, &data_ptr, some_data_len); 143 | ``` 144 | 145 | ### If you need to allocate memory in some function, and return pointer to allocated memory from it - just use [usmartpointer](https://github.com/SkyEng1neering/usmartpointer), this is an c++ wrapper for dalloc, and you can use it more comfortable: 146 | 147 | ```c++ 148 | SmartPointer func_that_use_dalloc(heap_t *heap_ptr, uint32_t some_data_len){ 149 | SmartPointer ptr; 150 | ptr.assignAllocMemPointer(heap_ptr); 151 | ptr.allocate(some_data_len); 152 | 153 | /* Maybe some logic */ 154 | 155 | return ptr; 156 | } 157 | ``` 158 | All memory moments here is managed automatically 159 | -------------------------------------------------------------------------------- /example.c: -------------------------------------------------------------------------------- 1 | /* 2 | * example.cpp 3 | * 4 | * Created on: Sep 24, 2021 5 | * Author: SkyEngineering 6 | */ 7 | 8 | #include "dalloc.h" 9 | 10 | #define HEAP_SIZE 32 11 | 12 | uint8_t single_heap[SINGLE_HEAP_SIZE] = {0}; 13 | 14 | uint8_t heap_array[HEAP_SIZE]; 15 | heap_t heap; 16 | 17 | int main(){ 18 | /* Init heap memory */ 19 | heap_init(&heap, (void*)heap_array, HEAP_SIZE); 20 | 21 | /* Allocate memory region in heap memory */ 22 | uint8_t *first_data_ptr = NULL; 23 | uint32_t first_allocation_size = 8; 24 | dalloc(&heap, first_allocation_size, (void**)&first_data_ptr); 25 | 26 | /* Check if allocation is successful */ 27 | if(first_data_ptr == NULL){ 28 | printf("Can't allocate %u bytes\n", first_allocation_size); 29 | return 0; 30 | } 31 | 32 | printf("Memory allocated successfully, allocated %u bytes\n", first_allocation_size); 33 | 34 | /* Print info about all allocations in given heap memory */ 35 | print_dalloc_info(&heap); 36 | dump_heap(&heap); 37 | dump_dalloc_ptr_info(&heap); 38 | 39 | /* Fill first allocated region by test values */ 40 | printf("Fill first allocated region by test values\n"); 41 | memset(first_data_ptr, 0x1, first_allocation_size); 42 | 43 | /* Print info about all allocations in given heap memory */ 44 | print_dalloc_info(&heap); 45 | dump_heap(&heap); 46 | dump_dalloc_ptr_info(&heap); 47 | 48 | /* Reallocate first memory region */ 49 | printf("Reallocate first memory region\n"); 50 | uint32_t new_size_for_first_allocation = 11; 51 | if(drealloc(&heap, new_size_for_first_allocation, (void**)&first_data_ptr) != true){ 52 | printf("Memory reallocation error, can't allocate %u bytes\n", new_size_for_first_allocation); 53 | } 54 | 55 | printf("Memory reallocated successfully, allocated %u bytes\n", new_size_for_first_allocation); 56 | 57 | /* Print info about all allocations in given heap memory */ 58 | print_dalloc_info(&heap); 59 | dump_heap(&heap); 60 | dump_dalloc_ptr_info(&heap); 61 | 62 | /* Allocate second memory region in heap memory */ 63 | uint8_t *second_data_ptr = NULL; 64 | uint32_t second_allocation_size = 5; 65 | dalloc(&heap, second_allocation_size, (void**)&second_data_ptr); 66 | 67 | /* Check if allocation is successful */ 68 | if(second_data_ptr == NULL){ 69 | printf("Can't allocate %u bytes\n", second_allocation_size); 70 | return 0; 71 | } 72 | 73 | printf("Memory allocated successfully, allocated %u bytes\n", second_allocation_size); 74 | 75 | /* Print info about all allocations in given heap memory */ 76 | print_dalloc_info(&heap); 77 | dump_heap(&heap); 78 | dump_dalloc_ptr_info(&heap); 79 | 80 | /* Fill second allocated region by test values */ 81 | printf("Fill second allocated region by test values\n"); 82 | memset(second_data_ptr, 0x2, second_allocation_size); 83 | 84 | /* Print info about all allocations in given heap memory */ 85 | print_dalloc_info(&heap); 86 | dump_heap(&heap); 87 | dump_dalloc_ptr_info(&heap); 88 | 89 | /* Free first memory region */ 90 | printf("Free first memory region\n"); 91 | dfree(&heap, (void**)&first_data_ptr, USING_PTR_ADDRESS); 92 | 93 | /* Print info about all allocations in given heap memory */ 94 | print_dalloc_info(&heap); 95 | dump_heap(&heap); 96 | dump_dalloc_ptr_info(&heap); 97 | 98 | /* Free second memory region */ 99 | printf("Free second memory region\n"); 100 | dfree(&heap, (void**)&second_data_ptr, USING_PTR_ADDRESS); 101 | 102 | /* Print info about all allocations in given heap memory */ 103 | print_dalloc_info(&heap); 104 | dump_heap(&heap); 105 | dump_dalloc_ptr_info(&heap); 106 | 107 | return 0; 108 | } 109 | -------------------------------------------------------------------------------- /inc/dalloc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Alexey Vasilenko 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef DALLOC_H 18 | #define DALLOC_H 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #include "dalloc_types.h" 25 | 26 | #ifdef USE_SINGLE_HEAP_MEMORY 27 | extern heap_t default_heap; 28 | extern uint8_t single_heap[]; 29 | 30 | void def_dalloc(uint32_t size, void **ptr); 31 | void def_dfree(void **ptr); 32 | void def_replace_pointers(void **ptr_to_replace, void **ptr_new); 33 | bool def_drealloc(uint32_t size, void **ptr); 34 | void print_def_dalloc_info(); 35 | void dump_def_heap(); 36 | void dump_def_dalloc_ptr_info(); 37 | #endif 38 | 39 | 40 | void heap_init(heap_t *heap_struct_ptr, void *mem_ptr, uint32_t mem_size); 41 | void dalloc(heap_t *heap_struct_ptr, uint32_t size, void **ptr); 42 | bool drealloc(heap_t *heap_struct_ptr, uint32_t size, void **ptr); 43 | bool validate_ptr(heap_t *heap_struct_ptr, void **ptr, validate_ptr_condition_t condition, uint32_t *ptr_index); 44 | void dfree(heap_t *heap_struct_ptr, void **ptr, validate_ptr_condition_t condition); 45 | void print_dalloc_info(heap_t *heap_struct_ptr); 46 | void dump_dalloc_ptr_info(heap_t* heap_struct_ptr); 47 | void dump_heap(heap_t* heap_struct_ptr); 48 | void replace_pointers(heap_t *heap_struct_ptr, void **ptr_to_replace, void **ptr_new); 49 | 50 | #ifdef __cplusplus 51 | } 52 | #endif 53 | 54 | #endif // DALLOC_H 55 | -------------------------------------------------------------------------------- /inc/dalloc_conf.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Alexey Vasilenko 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef DALLOCCONF_H 18 | #define DALLOCCONF_H 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #define DALLOC_VERSION "1.3.0" 25 | 26 | #define FILL_FREED_MEMORY_BY_NULLS true 27 | #define dalloc_debug printf 28 | #define MAX_NUM_OF_ALLOCATIONS 100UL 29 | 30 | /* Comment "USE_ALIGNMENT" define if you don't need to use alignment */ 31 | #define USE_ALIGNMENT 32 | 33 | #ifdef USE_ALIGNMENT 34 | #define ALLOCATION_ALIGNMENT_BYTES 4U 35 | #endif 36 | 37 | /* Uncomment "USE_SINGLE_HEAP_MEMORY" define if you want to use only 1 heap memory area */ 38 | #define USE_SINGLE_HEAP_MEMORY 39 | 40 | #ifdef USE_SINGLE_HEAP_MEMORY 41 | #define SINGLE_HEAP_SIZE (64UL*1024UL) 42 | #endif 43 | 44 | #ifdef __cplusplus 45 | } 46 | #endif 47 | 48 | #endif // DALLOCCONF_H 49 | -------------------------------------------------------------------------------- /inc/dalloc_types.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Alexey Vasilenko 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef DALLOCTYPES_H 18 | #define DALLOCTYPES_H 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | #include "stdint.h" 25 | #include "stdbool.h" 26 | #include "stdio.h" 27 | #include "string.h" 28 | #include "dalloc_conf.h" 29 | 30 | typedef enum { 31 | DALLOC_OK = 0, 32 | DALLOC_ERR 33 | } dalloc_stat_t; 34 | 35 | typedef enum { 36 | USING_PTR_ADDRESS = 0, 37 | USING_PTR_VALUE 38 | } validate_ptr_condition_t; 39 | 40 | typedef struct { 41 | uint8_t **ptr; 42 | uint32_t allocated_size; 43 | bool free_flag; 44 | } ptr_info_t; 45 | 46 | typedef struct { 47 | ptr_info_t ptr_info_arr[MAX_NUM_OF_ALLOCATIONS]; 48 | uint32_t allocations_num; 49 | uint32_t max_memory_amount; 50 | uint32_t max_allocations_amount; 51 | } alloc_info_t; 52 | 53 | typedef struct { 54 | uint8_t *mem; /* Pointer to the memory area using for heap */ 55 | uint32_t offset; /* Size of currently allocated memory */ 56 | uint32_t total_size; /* Total size of memory that can be used for allocation memory */ 57 | alloc_info_t alloc_info; 58 | } heap_t; 59 | 60 | #ifdef __cplusplus 61 | } 62 | #endif 63 | 64 | #endif // DALLOCTYPES_H 65 | -------------------------------------------------------------------------------- /src/dalloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2021 Alexey Vasilenko 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "dalloc.h" 18 | 19 | #ifdef USE_SINGLE_HEAP_MEMORY 20 | /* define single_heap array somewhere in your code, like on the example below: 21 | uint8_t single_heap[SINGLE_HEAP_SIZE] = {0}; 22 | */ 23 | heap_t default_heap; 24 | bool memory_init_flag = false; 25 | 26 | void def_dalloc(uint32_t size, void **ptr){ 27 | dalloc(&default_heap, size, ptr); 28 | } 29 | 30 | void def_dfree(void **ptr){ 31 | dfree(&default_heap, ptr, USING_PTR_ADDRESS); 32 | } 33 | 34 | void def_replace_pointers(void **ptr_to_replace, void **ptr_new){ 35 | replace_pointers(&default_heap, ptr_to_replace, ptr_new); 36 | } 37 | 38 | bool def_drealloc(uint32_t size, void **ptr){ 39 | return drealloc(&default_heap, size, ptr); 40 | } 41 | 42 | void print_def_dalloc_info(){ 43 | print_dalloc_info(&default_heap); 44 | } 45 | 46 | void dump_def_heap(){ 47 | dump_heap(&default_heap); 48 | } 49 | 50 | void dump_def_dalloc_ptr_info(){ 51 | dump_dalloc_ptr_info(&default_heap); 52 | } 53 | #endif 54 | 55 | void heap_init(heap_t* heap_struct_ptr, void *mem_ptr, uint32_t mem_size){//Init here mem structures 56 | heap_struct_ptr->offset = 0; 57 | heap_struct_ptr->mem = (uint8_t*)mem_ptr; 58 | heap_struct_ptr->total_size = mem_size; 59 | heap_struct_ptr->alloc_info.allocations_num = 0; 60 | heap_struct_ptr->alloc_info.max_memory_amount = 0; 61 | for(uint32_t i = 0; i < MAX_NUM_OF_ALLOCATIONS; i++){ 62 | heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr = NULL; 63 | heap_struct_ptr->alloc_info.ptr_info_arr[i].allocated_size = 0; 64 | heap_struct_ptr->alloc_info.ptr_info_arr[i].free_flag = true; 65 | } 66 | for(uint32_t i = 0; i < heap_struct_ptr->total_size; i++){ 67 | heap_struct_ptr->mem[i] = 0; 68 | } 69 | } 70 | 71 | void dalloc(heap_t* heap_struct_ptr, uint32_t size, void **ptr){ 72 | #ifdef USE_SINGLE_HEAP_MEMORY 73 | if(memory_init_flag == false){ 74 | heap_init(&default_heap, single_heap, SINGLE_HEAP_SIZE); 75 | memory_init_flag = true; 76 | } 77 | #endif 78 | 79 | if(!heap_struct_ptr || !size){ 80 | *ptr = NULL; 81 | } 82 | 83 | uint32_t new_offset = heap_struct_ptr->offset + size; 84 | 85 | /* Correct offset if use alignment */ 86 | #ifdef USE_ALIGNMENT 87 | while(new_offset % ALLOCATION_ALIGNMENT_BYTES != 0){ 88 | new_offset += 1; 89 | } 90 | #endif 91 | 92 | /* Check if there is enough memory for new allocation, and if number of allocations is exceeded */ 93 | if((new_offset <= heap_struct_ptr->total_size) && (heap_struct_ptr->alloc_info.allocations_num < MAX_NUM_OF_ALLOCATIONS)) { 94 | *ptr = heap_struct_ptr->mem + heap_struct_ptr->offset; 95 | heap_struct_ptr->offset = new_offset; 96 | 97 | /* Save info about allocated memory */ 98 | heap_struct_ptr->alloc_info.ptr_info_arr[heap_struct_ptr->alloc_info.allocations_num].ptr = (uint8_t**)ptr; 99 | heap_struct_ptr->alloc_info.ptr_info_arr[heap_struct_ptr->alloc_info.allocations_num].allocated_size = size; 100 | heap_struct_ptr->alloc_info.ptr_info_arr[heap_struct_ptr->alloc_info.allocations_num].free_flag = false; 101 | heap_struct_ptr->alloc_info.allocations_num = heap_struct_ptr->alloc_info.allocations_num + 1; 102 | 103 | if(heap_struct_ptr->offset > heap_struct_ptr->alloc_info.max_memory_amount){ 104 | heap_struct_ptr->alloc_info.max_memory_amount = heap_struct_ptr->offset; 105 | } 106 | if(heap_struct_ptr->alloc_info.allocations_num > heap_struct_ptr->alloc_info.max_allocations_amount){ 107 | heap_struct_ptr->alloc_info.max_allocations_amount = heap_struct_ptr->alloc_info.allocations_num; 108 | } 109 | } 110 | else { 111 | dalloc_debug("dalloc: Allocation failed\n"); 112 | print_dalloc_info(heap_struct_ptr); 113 | *ptr = NULL; 114 | if(new_offset > heap_struct_ptr->total_size){ 115 | dalloc_debug("dalloc: Heap size exceeded\n"); 116 | } 117 | if(heap_struct_ptr->alloc_info.allocations_num > MAX_NUM_OF_ALLOCATIONS){ 118 | dalloc_debug("dalloc: Max number of allocations exceeded: %lu\n", (long unsigned int)heap_struct_ptr->alloc_info.allocations_num); 119 | } 120 | } 121 | } 122 | 123 | bool validate_ptr(heap_t* heap_struct_ptr, void **ptr, validate_ptr_condition_t condition, uint32_t *ptr_index){ 124 | for(uint32_t i = 0; i < heap_struct_ptr->alloc_info.allocations_num; i++){ 125 | if(condition == USING_PTR_ADDRESS){ 126 | if(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr == (uint8_t**)ptr){ 127 | if(ptr_index != NULL){ 128 | *ptr_index = i; 129 | } 130 | return true; 131 | } 132 | } 133 | else { 134 | if(*(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr) == *ptr){ 135 | if(ptr_index != NULL){ 136 | *ptr_index = i; 137 | } 138 | return true; 139 | } 140 | } 141 | } 142 | return false; 143 | } 144 | 145 | bool is_ptr_address_in_heap_area(heap_t* heap_struct_ptr, void **ptr){ 146 | size_t heap_start_area = (size_t)(heap_struct_ptr->mem); 147 | size_t heap_stop_area = (size_t)(heap_struct_ptr->mem) + heap_struct_ptr->total_size; 148 | if(((size_t)ptr >= heap_start_area) && ((size_t)ptr <= heap_stop_area)){ 149 | return true; 150 | } 151 | return false; 152 | } 153 | 154 | void defrag_memory(heap_t* heap_struct_ptr){ 155 | for(uint32_t i = 0; i < heap_struct_ptr->alloc_info.allocations_num; i++){ 156 | if(heap_struct_ptr->alloc_info.ptr_info_arr[i].free_flag == true){ 157 | /* Optimize memory */ 158 | uint8_t *start_mem_ptr = *(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr); 159 | uint32_t start_ind = (uint32_t)(start_mem_ptr - heap_struct_ptr->mem); 160 | 161 | /* Set given ptr to NULL */ 162 | *(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr) = NULL; 163 | 164 | uint32_t alloc_size = heap_struct_ptr->alloc_info.ptr_info_arr[i].allocated_size; 165 | #ifdef USE_ALIGNMENT 166 | while(alloc_size % ALLOCATION_ALIGNMENT_BYTES != 0){ 167 | alloc_size += 1; 168 | } 169 | #endif 170 | /* Check if ptrs adresses of defragmentated memory are in heap region */ 171 | for(uint32_t k = i + 1; k < heap_struct_ptr->alloc_info.allocations_num; k++){ 172 | if(is_ptr_address_in_heap_area(heap_struct_ptr, (void**)heap_struct_ptr->alloc_info.ptr_info_arr[k].ptr)){ 173 | if((size_t)heap_struct_ptr->alloc_info.ptr_info_arr[k].ptr > (size_t)(start_mem_ptr)){ 174 | heap_struct_ptr->alloc_info.ptr_info_arr[k].ptr = (uint8_t**)((size_t)(heap_struct_ptr->alloc_info.ptr_info_arr[k].ptr) - alloc_size); 175 | } 176 | } 177 | } 178 | 179 | /* Defragmentate memory */ 180 | uint32_t stop_ind = heap_struct_ptr->offset - alloc_size; 181 | for(uint32_t k = start_ind; k <= stop_ind; k++){ 182 | *(heap_struct_ptr->mem + k) = *(heap_struct_ptr->mem + k + alloc_size); 183 | } 184 | 185 | /* Reassign pointers */ 186 | for(uint32_t k = i + 1; k < heap_struct_ptr->alloc_info.allocations_num; k++){ 187 | *(heap_struct_ptr->alloc_info.ptr_info_arr[k].ptr) -= alloc_size; 188 | } 189 | 190 | /* Actualize ptr info array */ 191 | for(uint32_t k = i; k < heap_struct_ptr->alloc_info.allocations_num - 1; k++){ 192 | heap_struct_ptr->alloc_info.ptr_info_arr[k] = heap_struct_ptr->alloc_info.ptr_info_arr[k + 1]; 193 | } 194 | 195 | /* Decrement allocations number */ 196 | heap_struct_ptr->alloc_info.allocations_num--; 197 | 198 | /* Refresh offset */ 199 | heap_struct_ptr->offset = heap_struct_ptr->offset - alloc_size; 200 | 201 | /* Fill by 0 all freed memory */ 202 | if(FILL_FREED_MEMORY_BY_NULLS){ 203 | for(uint32_t k = 0; k < alloc_size; k++){ 204 | heap_struct_ptr->mem[heap_struct_ptr->offset + k] = 0; 205 | } 206 | } 207 | } 208 | } 209 | } 210 | 211 | void dfree(heap_t* heap_struct_ptr, void **ptr, validate_ptr_condition_t condition){ 212 | /* Check if heap_ptr is not assigned */ 213 | if(heap_struct_ptr == NULL){ 214 | dalloc_debug("Heap pointer is not assigned\n"); 215 | return; 216 | } 217 | 218 | uint32_t ptr_index = 0; 219 | 220 | /* Try to find given ptr in ptr_info array */ 221 | if(validate_ptr(heap_struct_ptr, ptr, condition, &ptr_index) != true){ 222 | dalloc_debug("Try to free unexisting pointer\n"); 223 | return; 224 | } 225 | 226 | uint32_t alloc_size = heap_struct_ptr->alloc_info.ptr_info_arr[ptr_index].allocated_size; 227 | #ifdef USE_ALIGNMENT 228 | while(alloc_size % ALLOCATION_ALIGNMENT_BYTES != 0){ 229 | alloc_size += 1; 230 | } 231 | #endif 232 | 233 | /* Edit ptr info array */ 234 | heap_struct_ptr->alloc_info.ptr_info_arr[ptr_index].free_flag = true; 235 | #ifdef FILL_FREED_MEMORY_BY_NULLS 236 | for(uint32_t i = 0; i < alloc_size; i++){ 237 | *(*(heap_struct_ptr->alloc_info.ptr_info_arr[ptr_index].ptr) + i) = 0; 238 | } 239 | #endif 240 | 241 | // /* Set given ptr to NULL */ 242 | // if(condition == USING_PTR_ADDRESS){ 243 | // *ptr = NULL; 244 | // } 245 | 246 | defrag_memory(heap_struct_ptr); 247 | } 248 | 249 | void _dfree(heap_t* heap_struct_ptr, void **ptr, validate_ptr_condition_t condition){ 250 | uint32_t ptr_index = 0; 251 | 252 | /* Try to find given ptr in ptr_info array */ 253 | if(validate_ptr(heap_struct_ptr, ptr, condition, &ptr_index) == true){ 254 | 255 | /* Optimize memory, to escape fragmentation. */ 256 | uint32_t start_ind = (uint32_t)((uint8_t*)*ptr - heap_struct_ptr->mem); 257 | uint32_t alloc_size = heap_struct_ptr->alloc_info.ptr_info_arr[ptr_index].allocated_size; 258 | #ifdef USE_ALIGNMENT 259 | while(alloc_size % ALLOCATION_ALIGNMENT_BYTES != 0){ 260 | alloc_size += 1; 261 | } 262 | #endif 263 | 264 | uint32_t stop_ind = heap_struct_ptr->offset - alloc_size; 265 | for(uint32_t i = start_ind; i <= stop_ind; i++){ 266 | heap_struct_ptr->mem[i] = heap_struct_ptr->mem[i + alloc_size]; 267 | } 268 | 269 | /* Remove ptr from ptr_info array */ 270 | for(uint32_t i = ptr_index; i < heap_struct_ptr->alloc_info.allocations_num - 1; i++){ 271 | heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr = heap_struct_ptr->alloc_info.ptr_info_arr[i + 1].ptr; 272 | heap_struct_ptr->alloc_info.ptr_info_arr[i].allocated_size = heap_struct_ptr->alloc_info.ptr_info_arr[i + 1].allocated_size; 273 | /* Reassign pointers */ 274 | *(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr) -= alloc_size; 275 | } 276 | heap_struct_ptr->alloc_info.allocations_num--; 277 | 278 | /* Refresh offset */ 279 | heap_struct_ptr->offset = heap_struct_ptr->offset - alloc_size; 280 | 281 | /* Fill by 0 all freed memory */ 282 | if(FILL_FREED_MEMORY_BY_NULLS){ 283 | for(uint32_t i = 0; i < heap_struct_ptr->total_size - heap_struct_ptr->offset; i++){ 284 | heap_struct_ptr->mem[heap_struct_ptr->offset + i] = 0; 285 | } 286 | } 287 | 288 | /* Set given ptr to NULL */ 289 | if(condition == USING_PTR_ADDRESS){ 290 | *ptr = NULL; 291 | } 292 | } 293 | else { 294 | dalloc_debug("Try to free unexisting pointer\n"); 295 | } 296 | } 297 | 298 | void replace_pointers(heap_t* heap_struct_ptr, void **ptr_to_replace, void **ptr_new){ 299 | uint32_t ptr_ind = 0; 300 | if(validate_ptr(heap_struct_ptr, ptr_to_replace, USING_PTR_ADDRESS, &ptr_ind) != true){ 301 | dalloc_debug("Can't replace pointers. No pointer found in buffer\n"); 302 | return; 303 | } 304 | *ptr_new = *ptr_to_replace; 305 | heap_struct_ptr->alloc_info.ptr_info_arr[ptr_ind].ptr = (uint8_t**)ptr_new; 306 | *ptr_to_replace = NULL; 307 | } 308 | 309 | bool drealloc(heap_t* heap_struct_ptr, uint32_t size, void **ptr){ 310 | uint32_t size_of_old_block = 0; 311 | uint32_t old_ptr_ind = 0; 312 | if(validate_ptr(heap_struct_ptr, ptr, USING_PTR_ADDRESS, &old_ptr_ind) == true){ 313 | size_of_old_block = heap_struct_ptr->alloc_info.ptr_info_arr[old_ptr_ind].allocated_size; 314 | } 315 | else { 316 | return false; 317 | } 318 | 319 | uint8_t *new_ptr = NULL; 320 | dalloc(heap_struct_ptr, size, (void**)&new_ptr); 321 | 322 | uint8_t *old_ptr = (uint8_t *)(*ptr); 323 | 324 | for(uint32_t i = 0; i < size_of_old_block; i++){ 325 | new_ptr[i] = old_ptr[i]; 326 | } 327 | dfree(heap_struct_ptr, ptr, USING_PTR_ADDRESS); 328 | replace_pointers(heap_struct_ptr, (void**)&new_ptr, ptr); 329 | return true; 330 | } 331 | 332 | void print_dalloc_info(heap_t* heap_struct_ptr){ 333 | dalloc_debug("\n***************************** Mem Info *****************************\n"); 334 | dalloc_debug("Total memory, bytes: %lu\n", (long unsigned int)heap_struct_ptr->total_size); 335 | dalloc_debug("Memory in use, bytes: %lu\n", (long unsigned int)heap_struct_ptr->offset); 336 | dalloc_debug("Number of allocations: %lu\n", (long unsigned int)heap_struct_ptr->alloc_info.allocations_num); 337 | dalloc_debug("The biggest memory was in use: %lu\n", (long unsigned int)heap_struct_ptr->alloc_info.max_memory_amount); 338 | dalloc_debug("Max allocations number: %lu\n", (long unsigned int)heap_struct_ptr->alloc_info.max_allocations_amount); 339 | dalloc_debug("\n********************************************************************\n\n"); 340 | } 341 | 342 | void dump_heap(heap_t* heap_struct_ptr){ 343 | for(uint32_t i = 0; i < heap_struct_ptr->total_size; i++){ 344 | dalloc_debug("%02X ", heap_struct_ptr->mem[i]); 345 | } 346 | dalloc_debug("\n"); 347 | } 348 | 349 | void dump_dalloc_ptr_info(heap_t* heap_struct_ptr){ 350 | dalloc_debug("\n***************************** Ptr Info *****************************\n"); 351 | for(uint32_t i = 0; i < heap_struct_ptr->alloc_info.allocations_num; i++){ 352 | dalloc_debug("Ptr address: 0x%08X, ptr first val: 0x%02X, alloc size: %lu\n", (size_t)(heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr), (uint8_t)(**heap_struct_ptr->alloc_info.ptr_info_arr[i].ptr), (long unsigned int)heap_struct_ptr->alloc_info.ptr_info_arr[i].allocated_size); 353 | } 354 | dalloc_debug("\n********************************************************************\n\n"); 355 | } 356 | --------------------------------------------------------------------------------