summaryrefslogtreecommitdiffstats
path: root/common/eurephia_nullsafe.c
diff options
context:
space:
mode:
Diffstat (limited to 'common/eurephia_nullsafe.c')
-rw-r--r--common/eurephia_nullsafe.c70
1 files changed, 70 insertions, 0 deletions
diff --git a/common/eurephia_nullsafe.c b/common/eurephia_nullsafe.c
new file mode 100644
index 0000000..92747e5
--- /dev/null
+++ b/common/eurephia_nullsafe.c
@@ -0,0 +1,70 @@
+/* eurephia_nullsafe.c
+ *
+ * standard C string functions, which is made NULL safe by checking
+ * if input value is NULL before performing the action.
+ *
+ * GPLv2 only - Copyright (C) 2009
+ * David Sommerseth <dazo@users.sourceforge.net>
+ *
+ * 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; version 2
+ * of the License.
+ *
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+
+/**
+ * @file eurephia_nullsafe.c
+ * @author David Sommerseth <dazo@users.sourceforge.net>
+ * @date 2009-09-07
+ *
+ * @brief standard C string functions, which is made NULL safe by checking
+ * if input value is NULL before performing the action.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <eurephia_context.h>
+#include <eurephia_log.h>
+
+/**
+ * Internal function, called via the malloc_nullsafe() macro.
+ *
+ * @param ctx eurephiaCTX, used for logging
+ * @param sz size of the memory region being allocated
+ * @param file debug info, which file is doing this call
+ * @param line debug info, which line in the file
+ *
+ * @return Returns a void pointer to the memory region on success, otherwise NULL
+ */
+void *__malloc_nullsafe(eurephiaCTX *ctx, size_t sz, const char *file, int line) {
+ void *buf = NULL;
+
+ buf = calloc(1, sz); /* Using calloc, also gives a zero'd memory region */
+ if( !buf ) {
+ if( ctx ) {
+ eurephia_log(ctx, LOG_FATAL, 40,
+ "Could not allocate memory region for %ld bytes (File %s, line %i)",
+ sz, file, line);
+ } else {
+ fprintf(stderr, "** FATAL ERROR ** "
+ "Could not allocate memory region for %ld bytes (File %s, line %i)",
+ sz, file, line);
+ }
+ } else {
+ DEBUG(ctx, 40, "Allocated %ld bytes of memory on address %p (File %s, line %i)",
+ sz, buf, file, line);
+ }
+ return buf;
+}