File: safemalloc.c

package info (click to toggle)
fvwm3 1.0.6a%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,408 kB
  • sloc: ansic: 141,349; perl: 4,891; sh: 4,568; makefile: 785; yacc: 688; lex: 187; sed: 11
file content (112 lines) | stat: -rw-r--r-- 1,941 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* Memory management routines...
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see: <http://www.gnu.org/licenses/>
 */

/* Originally from OpenBSD */

#include "config.h"

#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <err.h>
#include <errno.h>
#include <sys/param.h>
#include <stdint.h>

#include "safemalloc.h"

void *
fxmalloc(size_t length)
{
	void	*ptr;

	if (length == 0)
		errx(1, "malloc: zero size.");

	if ((ptr = malloc(length)) == NULL)
		err(1, "malloc: couldn't allocate");

	return (ptr);
}

void *
fxcalloc(size_t num, size_t length)
{
	void	*ptr;

	if (num == 0 || length == 0)
		errx(1, "calloc:  zero size");

	if (SIZE_MAX / num < length)
		errx(1, "num * length > SIZE_MAX");

	if ((ptr = calloc(num, length)) == NULL)
		err(1, "calloc:  couldn't allocate");

	return (ptr);
}

void *
fxrealloc(void *oldptr, size_t nmemb, size_t size)
{
	size_t	 newsize = nmemb * size;
	void	*newptr;

	if (newsize == 0)
		errx(1, "zero size");
	if (SIZE_MAX / nmemb < size)
		errx(1, "nmemb * size > SIZE_MAX");
	if ((newptr = realloc(oldptr, newsize)) == NULL)
		err(1, "fxrealloc failed");

	return (newptr);
}

char *
fxstrdup(const char *s)
{
	char	*ptr;
	size_t	 len;

	len = strlen(s) + 1;
	ptr = fxmalloc(len);

	strlcpy(ptr, s, len);

	return (ptr);
}

int
xasprintf(char **ret, const char *fmt, ...)
{
	va_list ap;
	int i;

	va_start(ap, fmt);
	i = xvasprintf(ret, fmt, ap);
	va_end(ap);

	return (i);
}

int
xvasprintf(char **ret, const char *fmt, va_list ap)
{
	int i;

	i = vasprintf(ret, fmt, ap);

	if (i < 0 || *ret == NULL) {
		fvwm_debug(__func__, "xasprintf: %s", strerror(errno));
		exit (1);
	}

	return (i);
}