aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKarel Kočí <cynerd@email.cz>2016-11-17 15:33:35 +0100
committerKarel Kočí <cynerd@email.cz>2016-11-17 15:33:35 +0100
commit3e3af1dab62cac49c72143dddfbe097b43c2bba2 (patch)
treeab98954b631f4619ae0c2f99bfba339e93baeedd
parent174cfe0d1c01cd94c26d35362c2be38d9028cfac (diff)
downloadgeml-3e3af1dab62cac49c72143dddfbe097b43c2bba2.tar.gz
geml-3e3af1dab62cac49c72143dddfbe097b43c2bba2.tar.bz2
geml-3e3af1dab62cac49c72143dddfbe097b43c2bba2.zip
Add allocate functions with check
-rw-r--r--src/utils.c29
-rw-r--r--src/utils.h12
2 files changed, 41 insertions, 0 deletions
diff --git a/src/utils.c b/src/utils.c
index 3d91753..c545961 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -64,3 +64,32 @@ void print_message(const char *file, const int line, enum Verbosity level, const
vfprintf(stderr, msg, args);
fputs("\n", stderr);
}
+
+void *smalloc_internal(const char *file, const int line, size_t size) {
+ void *r;
+ r = malloc(size);
+ if (!r)
+ error_out_of_memmory_internal(file, line);
+ return r;
+}
+
+void *scalloc_internal(const char *file, const int line, size_t nmemb, size_t size) {
+ void *r;
+ r = calloc(nmemb, size);
+ if (!r)
+ error_out_of_memmory_internal(file, line);
+ return r;
+}
+
+void *srealloc_internal(const char *file, const int line, void *ptr, size_t size) {
+ void *r;
+ r = realloc(ptr, size);
+ if (!r)
+ error_out_of_memmory_internal(file, line);
+ return r;
+}
+
+void error_out_of_memmory_internal(const char *file, const int line) {
+ print_message(file, line, V_DIE, "Memory allocation failed. Out of memory?");
+ abort();
+}
diff --git a/src/utils.h b/src/utils.h
index f93992d..f23a9cb 100644
--- a/src/utils.h
+++ b/src/utils.h
@@ -17,6 +17,7 @@
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
+#include <stdlib.h>
#ifndef _UTILS_H_
#define _UTILS_H_
@@ -51,4 +52,15 @@ void print_message(const char *file, const int line, enum Verbosity level, const
#define ASSERT(CHECK) do { if (!(CHECK)) { printf("Assertion failed on %s:%d\n", __FILE__, __LINE__); } } while(0)
+// Secure versions of malloc and calloc. They just wraps malloc and calloc and
+// checks return value. Returned NULL causes program to die.
+#define smalloc(SIZE) smalloc_internal(__FILE__, __LINE__, SIZE)
+#define scalloc(NMEMB, SIZE) scalloc_internal(__FILE__, __LINE__, NMEMB, SIZE)
+#define srealloc(PTR, SIZE) srealloc_internal(__FILE__, __LINE__, PTR, SIZE)
+#define error_out_of_memmory error_out_of_memmory_internal(__FILE__, __LINE__)
+void *smalloc_internal(const char *file, const int line, size_t size);
+void *scalloc_internal(const char *file, const int line, size_t nmemb, size_t size);
+void *srealloc_internal(const char *file, const int line, void *ptr, size_t size);
+void error_out_of_memmory_internal(const char *file, const int line);
+
#endif /* _UTILS_H_ */