code / bb

Lines2.7K C1.8K Shell331 YAML273 Markdown197 make44
(54 lines)
1 //
2 // utils.c
3 // Copyright 2021 Bruce Hill
4 // Released under the MIT license with the Commons Clause
5 //
6 // This file contains implementations of some convenience functions for more
7 // easily error checking.
8 //
10 #include <err.h>
11 #include <stdarg.h>
12 #include <stdlib.h>
14 //
15 // If the given argument is nonnegative, print the error message and exit with
16 // failure. Otherwise, return the given argument.
17 //
18 int check_nonnegative(int negative_err, const char *err_msg, ...) {
19 if (negative_err < 0) {
20 va_list args;
21 va_start(args, err_msg);
22 verr(EXIT_FAILURE, err_msg, args);
23 va_end(args);
25 return negative_err;
28 //
29 // If the given argument is NULL, print the error message and exit with
30 // failure. Otherwise return the given argument.
31 //
32 void *check_nonnull(void *p, const char *err_msg, ...) {
33 if (p == NULL) {
34 va_list args;
35 va_start(args, err_msg);
36 verr(EXIT_FAILURE, err_msg, args);
37 va_end(args);
39 return p;
42 //
43 // For a given pointer to a memory-allocated pointer, free its memory and set
44 // the pointer to NULL. (This is a safer alternative to free() that
45 // automatically NULLs out the pointer so it can't be used after freeing)
46 //
47 void delete(void *p) {
48 if (*(void **)p != NULL) {
49 free(*(void **)p);
50 *(void **)p = NULL;
54 // vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0