]> git.cworth.org Git - acre/blobdiff - xmalloc.h
Add preliminary implementation of acre
[acre] / xmalloc.h
diff --git a/xmalloc.h b/xmalloc.h
new file mode 100644 (file)
index 0000000..650616a
--- /dev/null
+++ b/xmalloc.h
@@ -0,0 +1,78 @@
+/* malloc routines with error checking
+ *
+ * Copyright © 2007 Mozilla Corporation
+ * Copyright © 2009 Carl D. Worth
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
+ *
+ * Authors:
+ *     Vladimir Vukicevic <vladimir@pobox.com>
+ *     Carl Worth <cworth@cworth.org>
+ */
+
+#ifndef XMALLOC_H
+#define XMALLOC_H
+
+#include <stdint.h>
+#include <stdlib.h>
+
+/* Allocate memory using malloc(), checking for errors.
+ *
+ * Errors: This function will exit(1) if out-of-memory occurs.
+ */
+void *
+xmalloc (size_t size);
+
+
+/* Allocates nmemb*size memory using xmalloc(), taking care to not
+ * overflow when doing the multiplication.
+ *
+ * size should be a constant so that the compiler can optimize
+ * out a constant division.
+ *
+ * Return value: A pointer to the newly allocated memory or NULL in
+ * case of overflow.
+ *
+ * Errors: This function will exit(1) if out-of-memory occurs.
+ */
+#define xmalloc_ab(nmemb, size) \
+  ((size) && (unsigned) (nmemb) >= INT32_MAX / (unsigned) (size) ? NULL : \
+   xmalloc((unsigned) (nmemb) * (unsigned) (size)))
+
+/* Re-allocate memory using realloc(), checking for errors.
+ *
+ * Errors: This function will exit(1) if out-of-memory occurs.
+ */
+void *
+xrealloc (void *ptr, size_t size);
+
+/* Reallocates ptr a block of nmemb*@size memory using xrealloc(), taking
+ * care to not overflow when doing the multiplication.
+ *
+ * size should be a constant so that the compiler can optimize
+ * out a constant division.
+ *
+ * Return value: A pointer to the newly allocated memory, or NULL in
+ * case of overflow (whereupon the original block of memory is left
+ * untouched).
+ *
+ * Errors: This function will exit(1) if out-of-memory occurs.
+ *
+ */
+#define xrealloc_ab(ptr, nmemb, size) \
+  ((size) && (unsigned) (nmemb) >= INT32_MAX / (unsigned) (size) ? NULL : \
+   xrealloc(ptr, (unsigned) (nmemb) * (unsigned) (size)))
+
+#endif /* XMALLOC_H */