1 /* SPDX-License-Identifier: BSD-3-Clause
2 * Copyright (c) 2016, Olivier MATZ <zer0@droids-corp.org>
5 #include <ecoli_init.h>
6 #include <ecoli_malloc.h>
12 static int init_done = 0;
14 struct ec_malloc_handler ec_malloc_handler;
16 int ec_malloc_register(ec_malloc_t usr_malloc, ec_free_t usr_free,
17 ec_realloc_t usr_realloc)
19 if (usr_malloc == NULL || usr_free == NULL || usr_realloc == NULL) {
29 ec_malloc_handler.malloc = usr_malloc;
30 ec_malloc_handler.free = usr_free;
31 ec_malloc_handler.realloc = usr_realloc;
36 void *__ec_malloc(size_t size, const char *file, unsigned int line)
38 return ec_malloc_handler.malloc(size, file, line);
41 void *ec_malloc_func(size_t size)
43 return __ec_malloc(size, __FILE__, __LINE__);
46 void __ec_free(void *ptr, const char *file, unsigned int line)
48 ec_malloc_handler.free(ptr, file, line);
51 void ec_free_func(void *ptr)
53 __ec_free(ptr, __FILE__, __LINE__);
56 void *__ec_calloc(size_t nmemb, size_t size, const char *file,
64 if (nmemb != 0 && size != (total / nmemb)) {
69 ptr = __ec_malloc(total, file, line);
73 memset(ptr, 0, total);
77 void *__ec_realloc(void *ptr, size_t size, const char *file, unsigned int line)
79 return ec_malloc_handler.realloc(ptr, size, file, line);
82 char *__ec_strdup(const char *s, const char *file, unsigned int line)
84 size_t sz = strlen(s) + 1;
87 s2 = __ec_malloc(sz, file, line);
96 char *__ec_strndup(const char *s, size_t n, const char *file, unsigned int line)
98 size_t sz = strnlen(s, n);
101 s2 = __ec_malloc(sz + 1, file, line);
111 static int ec_malloc_init_func(void)
117 static struct ec_init ec_malloc_init = {
118 .init = ec_malloc_init_func,
122 EC_INIT_REGISTER(ec_malloc_init);