| 1 | /** |
| 2 | libsmacker - A C library for decoding .smk Smacker Video files |
| 3 | Copyright (C) 2012-2017 Greg Kennedy |
| 4 | |
| 5 | See smacker.h for more information. |
| 6 | |
| 7 | smk_malloc.h |
| 8 | "Safe" implementations of malloc and free. |
| 9 | Verbose implementation of assert. |
| 10 | */ |
| 11 | |
| 12 | #ifndef SMK_MALLOC_H |
| 13 | #define SMK_MALLOC_Hcxx . . $ `smk_malloc.h:13:9`! |
| 14 | |
| 15 | /* assert */ |
| 16 | #include <assert.h> |
| 17 | /* calloc */ |
| 18 | #include <stdlib.h> |
| 19 | /* fprintf */ |
| 20 | #include <stdio.h> |
| 21 | |
| 22 | /* Error messages from calloc */ |
| 23 | #include <errno.h> |
| 24 | #include <string.h> |
| 25 | |
| 26 | /** |
| 27 | Safe free: attempts to prevent double-free by setting pointer to NULL. |
| 28 | Optionally warns on attempts to free a NULL pointer. |
| 29 | */ |
| 30 | #define smk_freecxx . . $ `smk_malloc.h:30:9`!(p) \ |
| 31 | { \ |
| 32 | assertcxx . . $ `/usr/include/assert.h:118:11`! (p); \ |
| 33 | free(p); \ |
| 34 | p = NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:419:9`!; \ |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | Safe malloc: exits if calloc() returns NULL. |
| 39 | Also initializes blocks to 0. |
| 40 | Optionally warns on attempts to malloc over an existing pointer. |
| 41 | Ideally, one should not exit() in a library. However, if you cannot |
| 42 | calloc(), you probably have bigger problems. |
| 43 | */ |
| 44 | #define smk_malloccxx . . $ `smk_malloc.h:44:9`!(p, x) \ |
| 45 | { \ |
| 46 | assertcxx . . $ `/usr/include/assert.h:118:11`! (p == NULLcxx . . $ `/usr/lib/gcc/x86_64-linux-gnu/15/include/stddef.h:419:9`!); \ |
| 47 | p = calloc(1, x); \ |
| 48 | if (!p) \ |
| 49 | { \ |
| 50 | fprintf(stderrcxx . . $ `<external>/232824719582829767/stdio.h:155:9`!, "libsmacker::smk_malloc(" #p ", %lu) - ERROR: calloc() returned NULL (file: %s, line: %lu)\n\tReason: [%d] %s\n", \ |
| 51 | (unsigned long) (x), __FILE__, (unsigned long)__LINE__, errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`!, strerror(errnocxx . . $ `<external>/17633486526465735210/errno.h:38:10`!)); \ |
| 52 | exit(EXIT_FAILUREcxx . . $ `<external>/10696550936717951914/stdlib.h:92:9`!); \ |
| 53 | } \ |
| 54 | } |
| 55 | |
| 56 | #endif |