]> git.8kb.co.uk Git - dataflex/df32func/blobdiff - src/c/memman.c
Add missing new files
[dataflex/df32func] / src / c / memman.c
diff --git a/src/c/memman.c b/src/c/memman.c
new file mode 100644 (file)
index 0000000..2497fc4
--- /dev/null
@@ -0,0 +1,66 @@
+/*-------------------------------------------------------------------------\r
+ * memman.c\r
+ *     wrappers around malloc/realloc/free\r
+ *\r
+ * Copyright (c) 2007-2015, glyn@8kb.co.uk\r
+ * Author: Glyn Astill <glyn@8kb.co.uk>\r
+ *\r
+ *-------------------------------------------------------------------------\r
+ */\r
+\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <assert.h>\r
+\r
+/*\r
+ * Wrappers around malloc/realloc/free\r
+ */\r
+void * wmalloc(unsigned int size) {\r
+    char         *result;\r
+\r
+    if ((result = malloc(size)) == NULL) {\r
+        fprintf(stderr, "Failed to malloc %d bytes\n", size);\r
+        exit(1);\r
+    }\r
+    return result;\r
+}\r
+\r
+void * wrealloc(void *iptr, unsigned int size) {\r
+    char         *result;\r
+\r
+    assert(iptr != NULL);\r
+\r
+    if ((result = realloc(iptr, size)) == NULL) {\r
+        fprintf(stderr, "Failed to realloc %d bytes\n", size);\r
+        exit(1);\r
+    }\r
+    return result;\r
+}\r
+\r
+void wfree(void *iptr){\r
+   assert(iptr != NULL);\r
+\r
+    if (iptr) {\r
+       free(iptr);\r
+    }\r
+    iptr = NULL;\r
+}\r
+\r
+/*\r
+ * Reallocate memory block pointed to by iptr in chunks of chunk_size when\r
+ * required_size is greater than value pointed to be allocated_size.\r
+ * Sets value of allocated_size to current allocation.\r
+ */\r
+void * reallocate_block(void *iptr, int *allocated_size, int required_size, int chunk_size) {\r
+    void        *result;\r
+\r
+    if (*allocated_size >= required_size)\r
+        return iptr;\r
+\r
+    *allocated_size += (((required_size-*allocated_size)/chunk_size)+1)*chunk_size;\r
+\r
+    result = wrealloc(iptr, *allocated_size);\r
+\r
+    return result;\r
+}\r