home · contact · privacy
Replace uses of variable-length arrays with try_malloc()/free().
[plomrogue] / src / common / try_malloc.c
index 2a219274bb84060fc8704781b790058e147f2c6b..70392be27618c8c3a0dba5c4cc40dd4118702721 100644 (file)
@@ -2,14 +2,23 @@
 
 #include "try_malloc.h"
 #include <stdlib.h> /* for malloc */
+#include <stdio.h> /* sprintf() */
+#include <string.h> /* strlen() */
 #include <sys/types.h> /* for size_t */
-#include "rexit.h" /* for exit_trouble() */
+#include "rexit.h" /* for exit_err() */
 
 
 
 extern void * try_malloc(size_t size, char * f)
 {
+    char * prefix = "Trouble with malloc() in ";
+    char * msg = malloc(strlen(prefix) + strlen(f) + 1 + 1);
+    exit_err(NULL == msg,
+             "Trouble in try_malloc() with malloc() for error message string.");
+    int test = sprintf(msg, "%s%s.", prefix, f);
+    exit_err(test < 0, "Trouble in try_malloc() with sprintf().");
     void * p = malloc(size);
-    exit_trouble(NULL == p, f, "malloc()");
+    exit_err(NULL == p, msg); /* Bypass exit_trouble() calling try_malloc(). */
+    free(msg);
     return p;
 }