1 /* 2 * Copyright (C) 2020 The Android Open Source Project 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 CHPP_MEMORY_H_ 18 #define CHPP_MEMORY_H_ 19 20 #include <stddef.h> 21 22 #ifdef __cplusplus 23 extern "C" { 24 #endif 25 26 /** 27 * Allocate memory 28 */ 29 void *chppMalloc(const size_t size); 30 31 /** 32 * Free memory. 33 * Note that is is expected that CHPP_FREE_AND_NULLIFY() is used exclusively 34 * instead of calling chppFree directly. This would ensure that buf is set to 35 * NULL afterwards. 36 */ 37 void chppFree(void *ptr); 38 39 /** 40 * Reallocate memory. 41 * Ideally should use realloc() for systems that efficiently support it. 42 * 43 * Sample implementation for systems that don't support realloc(): 44 * 45 * if (newSize == oldSize) return oldPtr; 46 * void *newPtr = NULL; 47 * if (newSize == 0) { 48 * free(oldPtr); 49 * } else { 50 * newPtr = malloc(newSize); 51 * if (newPtr) { 52 * newPtr = memcpy(newPtr, oldPtr, MIN(oldSize, newSize)); 53 * free(oldPtr); 54 * } 55 * } 56 * return newPtr; 57 * 58 * TODO: A future enhancement could be to store fragments separately (e.g. 59 * linked list) and bubble up all of them 60 */ 61 void *chppRealloc(void *oldPtr, const size_t newSize, const size_t oldSize); 62 63 #ifdef __cplusplus 64 } 65 #endif 66 67 #endif // CHPP_MEMORY_H_ 68