diff options
| -rw-r--r-- | include/moslib/mem/alloc.h | 38 | ||||
| -rw-r--r-- | src/mem/alloc.c | 44 |
2 files changed, 82 insertions, 0 deletions
diff --git a/include/moslib/mem/alloc.h b/include/moslib/mem/alloc.h index c542ea8..b3f4885 100644 --- a/include/moslib/mem/alloc.h +++ b/include/moslib/mem/alloc.h @@ -1,2 +1,40 @@ // moslib/mem/alloc.h // Helper functions for general memory management + +#include <stddef.h> + +#ifndef MOSLIB_MEM_ALLOC_H +#define MOSLIB_MEM_ALLOC_H + +#define MOSLIB_MAX_ALLOC_ATTEMPTS 3 + +// Tries to malloc MOSLIB_MAX_ALLOC_ATTEMPTS times +// If all attempts fail - exits with EXIT_FAILURE code +// +// Arguments: +// size +// count of bytes to malloc +// +// Returns: +// pointer to the allocated memory +#define safe_malloc(size) safe_malloc_fn(size, __FILE__, __LINE__, __func__) + +// Tries to realloc MOSLIB_MAX_ALLOC_ATTEMPTS times +// If all attempts fail - exits with EXIT_FAILURE code +// +// Arguments: +// ptr +// pointer to the memory to realloc +// +// size +// new desired count of bytes of memory +// +// Returns: +// pointer to the reallocated memory +#define safe_realloc(ptr, size) safe_realloc_fn(ptr, size, __FILE__, __LINE__, __func__) + +// Function prototypes for macros +extern void *safe_malloc_fn(size_t size, const char *file, int line, const char *func); +extern void *safe_realloc_fn(void *ptr, size_t size, const char *file, int line, const char *func); + +#endif // MOSLIB_MEM_ALLOC_H diff --git a/src/mem/alloc.c b/src/mem/alloc.c index e69de29..7acea02 100644 --- a/src/mem/alloc.c +++ b/src/mem/alloc.c @@ -0,0 +1,44 @@ +#include "moslib/mem/alloc.h" + +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#define ERR_MESS(fl, ln, fn, msg) "%s:%d - error in function %s:\n%s\n", fl, ln, fn, msg + +void *safe_malloc_fn(size_t size, const char *file, int line, const char *func) { + for (size_t i = 0; i < MOSLIB_MAX_ALLOC_ATTEMPTS; i++) { + void *p = malloc(size); + if (p) + return p; + if (i < MOSLIB_MAX_ALLOC_ATTEMPTS - 1) { + fprintf(stderr, ERR_MESS(file, line, func, "malloc failed - retrying in 1s...")); + sleep(1); + } + } + + char errmes[64]; + sprintf(errmes, "FATAL: malloc failed %d times - exiting...", MOSLIB_MAX_ALLOC_ATTEMPTS); + fprintf(stderr, ERR_MESS(file, line, func, errmes)); + exit(EXIT_FAILURE); +} + +void *safe_realloc_fn(void *ptr, size_t size, const char *file, int line, const char *func) { + if (!ptr) + return safe_malloc_fn(size, file, line, func); + + for (size_t i = 0; i < MOSLIB_MAX_ALLOC_ATTEMPTS; i++) { + void *p = realloc(ptr, size); + if (p) + return p; + if (i < MOSLIB_MAX_ALLOC_ATTEMPTS - 1) { + fprintf(stderr, ERR_MESS(file, line, func, "realloc failed - retrying in 1s...")); + sleep(1); + } + } + + char errmes[64]; + sprintf(errmes, "FATAL: realloc failed %d times - exiting...", MOSLIB_MAX_ALLOC_ATTEMPTS); + fprintf(stderr, ERR_MESS(file, line, func, errmes)); + exit(EXIT_FAILURE); +} |
