diff options
Diffstat (limited to 'src/util/util.c')
| -rw-r--r-- | src/util/util.c | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/util/util.c b/src/util/util.c new file mode 100644 index 0000000..7419d0c --- /dev/null +++ b/src/util/util.c | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | /* See LICENSE file for copyright and license details. */ | ||
| 2 | |||
| 3 | #include <stdarg.h> | ||
| 4 | #include <stdio.h> | ||
| 5 | #include <stdlib.h> | ||
| 6 | #include <string.h> | ||
| 7 | |||
| 8 | #include "util.h" | ||
| 9 | |||
| 10 | /* | ||
| 11 | * die() | ||
| 12 | * Function to print an error message and terminate the program. | ||
| 13 | * Takes a formatted string (`fmt`) and additional arguments (as in `printf`). | ||
| 14 | * This function uses variable arguments and will print the formatted error | ||
| 15 | * message to `stderr` and then exit the program with a non-zero status | ||
| 16 | * (typically 1). | ||
| 17 | * | ||
| 18 | * Usage: | ||
| 19 | * die("Error occurred in function %s", __func__); | ||
| 20 | */ | ||
| 21 | void die(const char *format_string, ...) { | ||
| 22 | va_list argument_list; | ||
| 23 | va_start(argument_list, format_string); | ||
| 24 | vfprintf(stderr, format_string, argument_list); | ||
| 25 | va_end(argument_list); | ||
| 26 | |||
| 27 | if (format_string[0] && format_string[strlen(format_string) - 1] == ':') { | ||
| 28 | fputc(' ', stderr); | ||
| 29 | perror(NULL); | ||
| 30 | } else | ||
| 31 | fputc('\n', stderr); | ||
| 32 | |||
| 33 | exit(1); | ||
| 34 | } | ||
| 35 | |||
| 36 | /* | ||
| 37 | * ecalloc() | ||
| 38 | * Function to allocate memory for an array of elements, initializing the memory | ||
| 39 | * to zero. This function works like `calloc()`, but it adds error handling. If | ||
| 40 | * memory allocation fails, it will call the `die()` function to print an error | ||
| 41 | * message and terminate the program. | ||
| 42 | * | ||
| 43 | * Parameters: | ||
| 44 | * - `num_elements`: The number of elements to allocate memory for. | ||
| 45 | * - `element_size`: The size of each element in bytes. | ||
| 46 | * | ||
| 47 | * Returns: | ||
| 48 | * - A pointer to the allocated memory (of type `void *`). | ||
| 49 | * - If the allocation fails, the program will terminate via `die()`. | ||
| 50 | * | ||
| 51 | * Usage: | ||
| 52 | * int *array = ecalloc(10, sizeof(int)); // Allocate memory for an array of | ||
| 53 | * 10 integers. | ||
| 54 | */ | ||
| 55 | void *ecalloc(size_t num_elements, size_t element_size) { | ||
| 56 | void *allocated_memory; | ||
| 57 | |||
| 58 | if (!(allocated_memory = calloc(num_elements, element_size))) | ||
| 59 | die("calloc:"); | ||
| 60 | |||
| 61 | return allocated_memory; | ||
| 62 | } | ||
