project_files/frontlib/util/util.c
changeset 7224 5143861c83bd
parent 7179 f84805e6df03
child 7227 1c859f572d72
--- a/project_files/frontlib/util/util.c	Mon Jun 11 00:06:22 2012 +0200
+++ b/project_files/frontlib/util/util.c	Tue Jun 12 11:25:05 2012 +0200
@@ -1,4 +1,5 @@
 #include "util.h"
+#include "logging.h"
 
 #include <stddef.h>
 #include <stdarg.h>
@@ -16,16 +17,20 @@
 
 char *flib_vasprintf(const char *fmt, va_list args) {
 	char *result = NULL;
-	int requiredSize = vsnprintf(NULL, 0, fmt, args)+1;				// Figure out how much memory we need,
-	if(requiredSize>=0) {
-		char *tmpbuf = malloc(requiredSize);						// allocate it
-		if(tmpbuf) {
-			if(vsnprintf(tmpbuf, requiredSize, fmt, args)>=0) {		// and then do the actual formatting.
+	if(!fmt) {
+		flib_log_e("null parameter in flib_vasprintf");
+	} else {
+		int requiredSize = vsnprintf(NULL, 0, fmt, args)+1;					// Figure out how much memory we need,
+		if(requiredSize<0) {
+			flib_log_e("Error formatting string with template \"%s\" in flib_vasprintf", fmt);
+		} else {
+			char *tmpbuf = flib_malloc(requiredSize);						// allocate it
+			if(tmpbuf && vsnprintf(tmpbuf, requiredSize, fmt, args)>=0) {	// and then do the actual formatting.
 				result = tmpbuf;
 				tmpbuf = NULL;
 			}
+			free(tmpbuf);
 		}
-		free(tmpbuf);
 	}
 	return result;
 }
@@ -41,9 +46,25 @@
 	if(!buf || size==0) {
 		return NULL;
 	}
-	void *result = malloc(size);
+	void *result = flib_malloc(size);
 	if(result) {
 		memcpy(result, buf, size);
 	}
 	return result;
 }
+
+void *flib_malloc(size_t size) {
+	void *result = malloc(size);
+	if(!result) {
+		flib_log_e("Out of memory trying to malloc %zu bytes.", size);
+	}
+	return result;
+}
+
+void *flib_calloc(size_t count, size_t elementsize) {
+	void *result = calloc(count, elementsize);
+	if(!result) {
+		flib_log_e("Out of memory trying to calloc %zu objects of %zu bytes each.", count, elementsize);
+	}
+	return result;
+}