| 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_H |
| 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_free(p) \ |
| 31 | { \ |
| 32 | assert (p); \ |
| 33 | free(p); \ |
| 34 | p = NULL; \ |
| 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_malloc(p, x) \ |
| 45 | { \ |
| 46 | assert (p == NULL); \ |
| 47 | p = calloc(1, x); \ |
| 48 | if (!p) \ |
| 49 | { \ |
| 50 | fprintf(stderr, "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__, errno, strerror(errno)); \ |
| 52 | exit(EXIT_FAILURE); \ |
| 53 | } \ |
| 54 | } |
| 55 | |
| 56 | #endif |