home · contact · privacy
70392be27618c8c3a0dba5c4cc40dd4118702721
[plomrogue] / src / common / try_malloc.c
1 /* src/common/try_malloc.c */
2
3 #include "try_malloc.h"
4 #include <stdlib.h> /* for malloc */
5 #include <stdio.h> /* sprintf() */
6 #include <string.h> /* strlen() */
7 #include <sys/types.h> /* for size_t */
8 #include "rexit.h" /* for exit_err() */
9
10
11
12 extern void * try_malloc(size_t size, char * f)
13 {
14     char * prefix = "Trouble with malloc() in ";
15     char * msg = malloc(strlen(prefix) + strlen(f) + 1 + 1);
16     exit_err(NULL == msg,
17              "Trouble in try_malloc() with malloc() for error message string.");
18     int test = sprintf(msg, "%s%s.", prefix, f);
19     exit_err(test < 0, "Trouble in try_malloc() with sprintf().");
20     void * p = malloc(size);
21     exit_err(NULL == p, msg); /* Bypass exit_trouble() calling try_malloc(). */
22     free(msg);
23     return p;
24 }