[Piglit] [PATCH 12/23] util: Add wrappers for malloc and calloc that catch errors

Chad Versace chad.versace at linux.intel.com
Fri Sep 28 10:44:58 PDT 2012


Memory allocation should rarely fail, but when it does the test should
immediately abort and explain why. This patch defines two utility wrapper
functions, piglit_malloc() and piglit_calloc(), that do exactly that when
allocation fails.

Signed-off-by: Chad Versace <chad.versace at linux.intel.com>
---
 tests/util/piglit-util.c | 26 ++++++++++++++++++++++++++
 tests/util/piglit-util.h | 15 +++++++++++++++
 2 files changed, 41 insertions(+)

diff --git a/tests/util/piglit-util.c b/tests/util/piglit-util.c
index 891ae22..e0e6c96 100644
--- a/tests/util/piglit-util.c
+++ b/tests/util/piglit-util.c
@@ -406,3 +406,29 @@ write_null:
 	va_end(va);
 	return size_written;
 }
+
+void*
+piglit_malloc(size_t size)
+{
+	void *x = malloc(size);
+
+	if (x == NULL) {
+		fprintf(stderr, "piglit: error: allocation failed\n");
+		abort();
+	}
+
+	return x;
+}
+
+void*
+piglit_calloc(size_t size)
+{
+	void *x = calloc(1, size);
+
+	if (x == NULL) {
+		fprintf(stderr, "piglit: error: allocation failed\n");
+		abort();
+	}
+
+	return x;
+}
diff --git a/tests/util/piglit-util.h b/tests/util/piglit-util.h
index 269a590..2a75933 100644
--- a/tests/util/piglit-util.h
+++ b/tests/util/piglit-util.h
@@ -148,6 +148,21 @@ piglit_source_dir(void);
 size_t
 piglit_join_paths(char buf[], size_t buf_size, int n, ...);
 
+/**
+ * If allocation fails, then print error message and exit.
+ */
+void*
+piglit_malloc(size_t size);
+
+/**
+ * If allocation fails, then print error message and exit.
+ *
+ * The signature of piglit_calloc() matches malloc() rather than calloc()
+ * because that is the signature that everyone really wants.
+ */
+void*
+piglit_calloc(size_t size);
+
 #ifdef __cplusplus
 } /* end extern "C" */
 #endif
-- 
1.7.12.1



More information about the Piglit mailing list