home · contact · privacy
License everything (GPL).
[plomrogue] / src / common / try_malloc.c
1 /* src/common/try_malloc.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #include "try_malloc.h"
9 #include <stdlib.h> /* for malloc */
10 #include <stdio.h> /* sprintf() */
11 #include <string.h> /* strlen() */
12 #include <sys/types.h> /* for size_t */
13 #include "rexit.h" /* for exit_err() */
14
15
16
17 extern void * try_malloc(size_t size, const char * f)
18 {
19     char * prefix = "Trouble with malloc in ";
20     char * msg = malloc(strlen(prefix) + strlen(f) + 1 + 1);
21     exit_err(!msg,
22              "Trouble in try_malloc with malloc for error message string.");
23     int test = sprintf(msg, "%s%s.", prefix, f);
24     exit_err(test < 0, "Trouble in try_malloc with sprintf.");
25     void * p = malloc(size);
26     exit_err(!p, msg);         /* Bypass exit_trouble() calling try_malloc(). */
27     free(msg);
28     return p;
29 }