memory.h (2852B)
1 /* 2 * Copyright (c) 2021-2024 lumidify <nobody@lumidify.org> 3 * 4 * Permission to use, copy, modify, and/or distribute this software for any 5 * purpose with or without fee is hereby granted, provided that the above 6 * copyright notice and this permission notice appear in all copies. 7 * 8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 */ 16 17 #ifndef LTK_MEMORY_H 18 #define LTK_MEMORY_H 19 20 #include <stdlib.h> 21 22 #if MEMDEBUG == 1 23 #define ltk_strdup(s) ltk_strdup_debug(s, __func__, __FILE__, __LINE__) 24 #define ltk_strndup(s, n) ltk_strndup_debug(s, n, __func__, __FILE__, __LINE__) 25 #define ltk_malloc(size) ltk_malloc_debug(size, __func__, __FILE__, __LINE__) 26 #define ltk_calloc(nmemb, size) ltk_calloc_debug(nmemb, size, __func__, __FILE__, __LINE__) 27 #define ltk_realloc(ptr, size) ltk_realloc_debug(ptr, size, __func__, __FILE__, __LINE__) 28 #define ltk_free(ptr) ltk_free_debug(ptr, __func__, __FILE__, __LINE__) 29 #else 30 #define ltk_strdup(s) ltk_strdup_impl(s) 31 #define ltk_strndup(s, n) ltk_strndup_impl(s, n) 32 #define ltk_malloc(size) ltk_malloc_impl(size); 33 #define ltk_calloc(nmemb, size) ltk_calloc_impl(nmemb, size); 34 #define ltk_realloc(ptr, size) ltk_realloc_impl(ptr, size); 35 #define ltk_free(ptr) free(ptr); 36 #endif 37 38 #define ltk_free0(p) do {ltk_free(p); p = NULL;} while (0) 39 40 char *ltk_strdup_impl(const char *s); 41 char *ltk_strndup_impl(const char *s, size_t n); 42 void *ltk_malloc_impl(size_t size); 43 void *ltk_calloc_impl(size_t nmemb, size_t size); 44 void *ltk_realloc_impl(void *ptr, size_t size); 45 46 char *ltk_strdup_debug(const char *s, const char *caller, const char *file, int line); 47 char *ltk_strndup_debug(const char *s, size_t n, const char *caller, const char *file, int line); 48 void *ltk_malloc_debug(size_t size, const char *caller, const char *file, int line); 49 void *ltk_calloc_debug(size_t nmemb, size_t size, const char *caller, const char *file, int line); 50 void *ltk_realloc_debug(void *ptr, size_t size, const char *caller, const char *file, int line); 51 void ltk_free_debug(void *ptr, const char *caller, const char *file, int line); 52 void *ltk_reallocarray(void *optr, size_t nmemb, size_t size); 53 54 size_t ideal_array_size(size_t old, size_t needed); 55 56 /* This acts like snprintf but automatically allocates 57 a string of the appropriate size. 58 Like the other functions here, it exits on error. */ 59 char *ltk_print_fmt(char *fmt, ...); 60 61 #endif /* LTK_MEMORY_H */