Improved error checking

This commit is contained in:
Bruce Hill 2021-07-30 14:54:28 -07:00
parent 3445982b16
commit 33a63bb8d9
4 changed files with 21 additions and 10 deletions

2
bp.c
View File

@ -458,7 +458,7 @@ static int process_git_files(def_t *defs, pat_t *pattern, int argc, char *argv[]
if (child == -1)
err(EXIT_FAILURE, "Failed to fork");
if (child == 0) {
const char **git_args = memcheck(calloc((size_t)(2+argc+1), sizeof(char*)));
const char **git_args = new(char*[2+argc+1]);
int g = 0;
git_args[g++] = "git";
git_args[g++] = "ls-files";

View File

@ -88,7 +88,7 @@ file_t *load_file(file_t **files, const char *filename)
}
size_t length;
file_t *f = new(file_t);
f->filename = memcheck(strdup(filename));
f->filename = checked_strdup(filename);
struct stat sb;
if (fstat(fd, &sb) == -1)
@ -150,7 +150,7 @@ file_t *spoof_file(file_t **files, const char *filename, const char *text, ssize
if (filename == NULL) filename = "";
file_t *f = new(file_t);
size_t len = _len == -1 ? strlen(text) : (size_t)_len;
f->filename = memcheck(strdup(filename));
f->filename = checked_strdup(filename);
f->memory = new(char[len+1]);
memcpy(f->memory, text, len);
f->start = &f->memory[0];

14
utils.c
View File

@ -4,6 +4,7 @@
#include <ctype.h>
#include <err.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
@ -124,12 +125,17 @@ char unescapechar(const char *escaped, const char **end)
}
//
// Fail and exit if a memory value is NULL
// If the given argument is NULL, print the error message and exit with
// failure. Otherwise return the given argument.
//
void *memcheck(void *p)
void *check_nonnull(void *p, const char *err_msg, ...)
{
if (p == NULL)
err(EXIT_FAILURE, "memory allocation failure");
if (p == NULL) {
va_list args;
va_start(args, err_msg);
verr(EXIT_FAILURE, err_msg, args);
va_end(args);
}
return p;
}

11
utils.h
View File

@ -12,9 +12,14 @@
#include "match.h"
#define S1(x) #x
#define S2(x) S1(x)
#define __LOCATION__ __FILE__ ":" S2(__LINE__)
#define streq(a, b) (strcmp(a, b) == 0)
#define new(t) memcheck(calloc(1, sizeof(t)))
#define grow(arr,n) memcheck(realloc(arr,sizeof(arr[0])*(n)))
#define new(t) check_nonnull(calloc(1, sizeof(t)), __LOCATION__ ": `new(" #t ")` allocation failure")
#define checked_strdup(s) check_nonnull(strdup(s), __LOCATION__ ": `checked_strdup(" #s ")` allocation failure")
#define grow(arr,n) check_nonnull(realloc(arr,sizeof(arr[0])*(n)), __LOCATION__ ": `groaw(" #arr ", " #n ")` allocation failure")
__attribute__((nonnull(1)))
char unescapechar(const char *escaped, const char **end);
@ -27,7 +32,7 @@ bool matchchar(const char **str, char c);
__attribute__((nonnull))
bool matchstr(const char **str, const char *target);
__attribute__((returns_nonnull))
void *memcheck(/*@null@*/ /*@out@*/ void *p);
void *check_nonnull(void *p, const char *err_msg, ...);
__attribute__((nonnull))
int memicmp(const void *s1, const void *s2, size_t n);
__attribute__((nonnull))