[dev][libsl][PATCH] drw.c: Allocation success check, don't call die() on error

From: Lorenzo Cogotti <miciamail_AT_hotmail.it>
Date: Fri, 12 Apr 2013 16:56:55 +0200

This commit modifies drw.c to avoid killing the application
if an error occurs, the caller should be able to decide what to do
on error situations, this hopefully improves code reusability on various
projects. It also checks for calloc() to succeed before using the returned
pointer, improving code reliability.
Some minor and trivial style updates have been added, eliminating redundant
calls to free() and avoiding if (!ptr) return; on simple one-liner functions.
---
 drw.c | 40 +++++++++++++++++++++++-----------------
 1 file changed, 23 insertions(+), 17 deletions(-)
diff --git a/drw.c b/drw.c
index 65fd870..857dd19 100644
--- a/drw.c
+++ b/drw.c
_AT_@ -10,6 +10,8 @@
 Drw *
 drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h) {
 	Drw *drw = (Drw *)calloc(1, sizeof(Drw));
+	if(!drw)
+		return NULL;
 	drw->dpy = dpy;
 	drw->screen = screen;
 	drw->win = win;
_AT_@ -47,6 +49,8 @@ drw_font_create(Drw *drw, const char *fontname) {
 	if(!drw)
 		return NULL;
 	font = (Fnt *)calloc(1, sizeof(Fnt));
+	if(!font)
+		return NULL;
 	font->set = XCreateFontSet(drw->dpy, fontname, &missing, &n, &def);
 	if(missing) {
 		while(n--)
_AT_@ -66,8 +70,10 @@ drw_font_create(Drw *drw, const char *fontname) {
 	}
 	else {
 		if(!(font->xfont = XLoadQueryFont(drw->dpy, fontname))
-		&& !(font->xfont = XLoadQueryFont(drw->dpy, "fixed")))
-			die("error, cannot load font: '%s'\n", fontname);
+		&& !(font->xfont = XLoadQueryFont(drw->dpy, "fixed"))) {
+			free(font);
+			return NULL;
+		}
 		font->ascent = font->xfont->ascent;
 		font->descent = font->xfont->descent;
 	}
_AT_@ -88,42 +94,42 @@ drw_font_free(Drw *drw, Fnt *font) {
 
 Clr *
 drw_clr_create(Drw *drw, const char *clrname) {
-	Clr *clr = (Clr *)calloc(1, sizeof(Clr));
-	Colormap cmap = DefaultColormap(drw->dpy, drw->screen);
+	Colormap cmap;
+	Clr *clr;
 	XColor color;
 
+	if(!drw)
+		return NULL;
+	cmap = DefaultColormap(drw->dpy, drw->screen);
 	if(!XAllocNamedColor(drw->dpy, cmap, clrname, &color, &color))
-		die("error, cannot allocate color '%s'\n", clrname);
-	clr->rgb = color.pixel;
+		return NULL;
+	clr = (Clr *)calloc(1, sizeof(Clr));
+	if(clr)
+		clr->rgb = color.pixel;
 	return clr;
 }
 
 void
 drw_clr_free(Drw *drw, Clr *clr) {
-	if(!clr)
-		return;
 	free(clr);
 }
 
 void
 drw_setfont(Drw *drw, Fnt *font) {
-	if(!drw)
-		return;
-	drw->font = font;
+	if(drw)
+		drw->font = font;
 }
 
 void
 drw_setfg(Drw *drw, Clr *clr) {
-	if(!drw) 
-		return;
-	drw->fg = clr;
+	if(drw)
+		drw->fg = clr;
 }
 
 void
 drw_setbg(Drw *drw, Clr *clr) {
-	if(!drw)
-		return;
-	drw->bg = clr;
+	if(drw)
+		drw->bg = clr;
 }
 
 void
-- 
1.8.1.5
Received on Fri Apr 12 2013 - 16:56:55 CEST

This archive was generated by hypermail 2.3.0 : Fri Apr 12 2013 - 17:12:06 CEST