diff options
| author | Mosder <xmosder12@gmail.com> | 2026-08-21 11:50:51 +0200 |
|---|---|---|
| committer | Mosder <xmosder12@gmail.com> | 2026-08-21 11:50:51 +0200 |
| commit | b6b7a01987dca604a161c8c73a240ec4430baed0 (patch) | |
| tree | b9fdeb674ad767ccb16d1a3cdc2c6c975ea11737 /src/safe.c | |
| parent | 890a52b9af6e24015048eb2754552b9613484b3f (diff) | |
refactor: renamed mem/alloc.h to safe.h and made it be a collection of "safe" wrappers for "unsafe" functions
Diffstat (limited to 'src/safe.c')
| -rw-r--r-- | src/safe.c | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/safe.c b/src/safe.c new file mode 100644 index 0000000..7c7627e --- /dev/null +++ b/src/safe.c @@ -0,0 +1,42 @@ +#define MOS_FORCE_PREFIXES +#include "moslib/safe.h" + +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +#define ERR_MESS(msg, ...) err_mess(info, msg, __VA_ARGS__) + +void err_mess(MosSafeErrInfo info, const char *msg, ...) { + va_list args; + va_start(args, msg); + fprintf(stderr, "%s:%d - fatal error in function %s:\n", info.file, info.line, info.func); + vfprintf(stderr, msg, args); + fprintf(stderr, "\n"); + va_end(args); +} + +void *mos_safe_malloc_fn(size_t size, MosSafeErrInfo info) { + void *p = malloc(size); + if (p) + return p; + ERR_MESS("failed to malloc %zu bytes", size); + exit(EXIT_FAILURE); +} + +void *mos_safe_calloc_fn(size_t count, size_t size, MosSafeErrInfo info) { + void *p = calloc(count, size); + if (p) + return p; + ERR_MESS("failed to calloc %zu items of %zu size", count, size); + exit(EXIT_FAILURE); +} + +void *mos_safe_realloc_fn(void *ptr, size_t size, MosSafeErrInfo info) { + void *p = realloc(ptr, size); + if (p) + return p; + ERR_MESS("failed to realloc %p to %zu bytes", ptr, size); + exit(EXIT_FAILURE); +} |
