-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxalloc.h
47 lines (41 loc) · 1.28 KB
/
xalloc.h
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
/**************************************************************************/
/* COPYRIGHT Carnegie Mellon University 2023 */
/* Do not post this file or any derivative on a public site or repository */
/**************************************************************************/
/* Allocation utilities
* Implement versions of malloc and free that abort
* when allocation fails instead of returning NULL.
*
* 15-122 Principles of Imperative Computation, Fall 2010
* Frank Pfenning
*/
#ifndef XALLOC_H
#define XALLOC_H
#include <stdlib.h>
#include <stdio.h>
/* xcalloc(nobj, size) returns a non-NULL pointer to
* array of nobj objects, each of size size and
* exits if the allocation fails. Like calloc, the
* array is initialized with zeroes.
*/
static inline void* xcalloc(size_t nobj, size_t size) {
void* p = calloc(nobj, size);
if (p == NULL) {
fprintf(stderr, "allocation failed\n");
abort();
}
return p;
}
/* xmalloc(size) returns a non-NULL pointer to
* an object of size size and exits if the allocation
* fails. Like malloc, no initialization is guaranteed.
*/
static inline void* xmalloc(size_t size) {
void* p = malloc(size);
if (p == NULL) {
fprintf(stderr, "allocation failed\n");
abort();
}
return p;
}
#endif