diff mbox

[v2,1/2] utils: provide array allocation wrapper

Message ID 20170102195409.14669-2-oleksandr@natalenko.name
State Not Applicable
Delegated to: Florian Westphal
Headers show

Commit Message

Oleksandr Natalenko Jan. 2, 2017, 7:54 p.m. UTC
This will be used for allocating memory for arrays
in heap instead of keeping them on stack.

Signed-off-by: Oleksandr Natalenko <oleksandr@natalenko.name>
---
 include/utils.h |  1 +
 src/utils.c     | 10 ++++++++++
 2 files changed, 11 insertions(+)
diff mbox

Patch

diff --git a/include/utils.h b/include/utils.h
index bb58ba4..3199388 100644
--- a/include/utils.h
+++ b/include/utils.h
@@ -138,6 +138,7 @@  extern void __memory_allocation_error(const char *filename, uint32_t line) __nor
 
 extern void xfree(const void *ptr);
 extern void *xmalloc(size_t size);
+extern void *xmalloc_array(size_t nmemb, size_t size);
 extern void *xrealloc(void *ptr, size_t size);
 extern void *xzalloc(size_t size);
 extern char *xstrdup(const char *s);
diff --git a/src/utils.c b/src/utils.c
index 65dabf4..16bc9e2 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -39,6 +39,16 @@  void *xmalloc(size_t size)
 	return ptr;
 }
 
+void *xmalloc_array(size_t nmemb, size_t size)
+{
+	assert(size != 0);
+
+	if (nmemb > SIZE_MAX / size)
+		memory_allocation_error();
+
+	return xmalloc(nmemb * size);
+}
+
 void *xrealloc(void *ptr, size_t size)
 {
 	ptr = realloc(ptr, size);