-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxalloc.h
76 lines (67 loc) · 1.53 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
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
#ifndef _XALLOC_H_
#define _XALLOC_H_
// printed error message when allocation is failed.
#define MEMORY_ERR "Out of memory!\n"
#include <stdlib.h> /* for allocating operations */
void *xmem_err(void *p);
void *xmalloc(size_t size);
void *xrealloc(void *target, size_t new_size);
void *xcalloc(size_t count, size_t size);
/**
* Throw exception and exit program if p is ``NULL`` pointer.
*
* Args:
* p(void *): target pointer
*
* Returns:
* ``p`` if ``p`` is not ``NULL``
*/
void *xmem_err(void *p) {
if (!p) {
fprintf(stderr, MEMORY_ERR);
exit(EXIT_FAILURE); /* 1 */
}
return p;
}
/**
* Allocate memory from heap and initialize with zero values.
*
* Args:
* size(size_t): allocation byte size
*
* Returns:
* head of allocated address
*/
void *xmalloc(size_t size) {
void *pointer = xmem_err(malloc(size));
memset(pointer, 0, size); /* set zero values */
return pointer;
}
/**
* Reallocate given pointer address.
*
* Args:
* target(void *): target pointer to be reallocated
* new_size(size_t): new allocation size
*
* Returns:
* head of reallocated address
*/
void *xrealloc(void *target, size_t new_size) {
return xmem_err(realloc(target, new_size));
}
/**
* Allocate memory from heap with count and
* automatic initialize with zero values.
*
* Args:
* count(size_t): allocation count
* size(size_t): allocation size
*
* Returns:
* head of allocated address
*/
void *xcalloc(size_t count, size_t size) {
return xmem_err(calloc(count, size));
}
#endif