/* See LICENSE file for copyright and license details. */ #include #include #include #include #include "util.h" /* * die() * Function to print an error message and terminate the program. * Takes a formatted string (`fmt`) and additional arguments (as in `printf`). * This function uses variable arguments and will print the formatted error * message to `stderr` and then exit the program with a non-zero status * (typically 1). * * Usage: * die("Error occurred in function %s", __func__); */ void die(const char *format_string, ...) { va_list argument_list; va_start(argument_list, format_string); vfprintf(stderr, format_string, argument_list); va_end(argument_list); if (format_string[0] && format_string[strlen(format_string) - 1] == ':') { fputc(' ', stderr); perror(NULL); } else fputc('\n', stderr); exit(1); } /* * ecalloc() * Function to allocate memory for an array of elements, initializing the memory * to zero. This function works like `calloc()`, but it adds error handling. If * memory allocation fails, it will call the `die()` function to print an error * message and terminate the program. * * Parameters: * - `num_elements`: The number of elements to allocate memory for. * - `element_size`: The size of each element in bytes. * * Returns: * - A pointer to the allocated memory (of type `void *`). * - If the allocation fails, the program will terminate via `die()`. * * Usage: * int *array = ecalloc(10, sizeof(int)); // Allocate memory for an array of * 10 integers. */ void *ecalloc(size_t num_elements, size_t element_size) { void *allocated_memory; if (!(allocated_memory = calloc(num_elements, element_size))) die("calloc:"); return allocated_memory; }