From 21e4fb267e3b2be8688c66a060567ada8349eb99 Mon Sep 17 00:00:00 2001 From: Werner Almesberger Date: Sun, 1 Jul 2012 20:43:04 -0300 Subject: [PATCH] tools/libtxt/: introduce utility functions alloc_size and alloc_type --- tools/libtxt/edit.c | 13 ++++--------- tools/libtxt/font.c | 4 +--- tools/libtxt/util.h | 20 +++++++++++++++++++- 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/tools/libtxt/edit.c b/tools/libtxt/edit.c index 4456bfd..b8b7605 100644 --- a/tools/libtxt/edit.c +++ b/tools/libtxt/edit.c @@ -16,6 +16,7 @@ #include #include +#include "util.h" #include "libtxt.h" @@ -116,9 +117,7 @@ static char *alloc_string_n(const char *s, size_t len) { char *t; - t = malloc(len+1); - if (!t) - abort(); + t = alloc_size(len+1); memcpy(t, s, len); t[len] = 0; return t; @@ -129,9 +128,7 @@ static void add_string(struct edit ***last, const char *start, size_t len) { struct edit *e; - e = malloc(sizeof(struct edit)); - if (!e) - abort(); + e = alloc_type(struct edit); e->type = edit_string; e->u.s = alloc_string_n(start, len); **last = e; @@ -187,9 +184,7 @@ struct edit *text2edit(const char *s) if (*s == '\n' && !have_text) continue; - e = malloc(sizeof(struct edit)); - if (!e) - abort(); + e = alloc_type(struct edit); e->type = edit_nl; /* pick something without data */ e->next = NULL; *last = e; diff --git a/tools/libtxt/font.c b/tools/libtxt/font.c index e8d68ff..69c8fe8 100644 --- a/tools/libtxt/font.c +++ b/tools/libtxt/font.c @@ -112,9 +112,7 @@ struct image *load_image(const char *name, const char **error) return NULL; } - img = malloc(sizeof(struct image)); - if (!img) - abort(); + img = alloc_type(struct image); err = read_xbm_file(file, img); if (err) { if (error) diff --git a/tools/libtxt/util.h b/tools/libtxt/util.h index 8d77b52..0c418b4 100644 --- a/tools/libtxt/util.h +++ b/tools/libtxt/util.h @@ -19,7 +19,25 @@ #include -static const char *alloc_sprintf(const char *fmt, ...) +static inline void *alloc_size(size_t size) +{ + void *tmp = malloc(size); + + if (!tmp) + abort(); + return tmp; +} + + +#define alloc_type(t) ((t *) alloc_size(sizeof(t))) + + +/* + * @@@ __attribute__((used)) is an ugly wait to get rid of the "unused + * function" warning. (The "unused" attribute doesn't do the trick.) + */ + +static const char * __attribute__((used)) alloc_sprintf(const char *fmt, ...) { va_list ap; char *tmp, *res;